DEV Community

Cover image for JavaScript DOM - Part 5 - Get Elements By ClassName [video + article]

JavaScript DOM - Part 5 - Get Elements By ClassName [video + article]

Tharun Shiv on May 21, 2020

This is going to be a multi-part Video + article tutorial series on JavaScript DOM. You're reading Part 5 You can read Part 4 here: ...
Collapse
 
uma_bcc profile image
umamaheswari.v

Good article, looking forward for more.. :)

Collapse
 
venkat121998 profile image
venkat anirudh

What if there is only one element with that class name, would it still return an HTML Collection? Good article, btw 🔥

Collapse
 
ziizium profile image
Habdul Hazeez • Edited

Yes, document.getElementsByClassName would still return an HTMLcollection if there is only one element with that class name.

Take the following code snippet.

<form class="myForm">
    <input type="text" placeholder="Name" />
    <input type="email" placeholder="Email Address" />
    <input type="submit" value="Subscribe" />
</form>
let myForm = document.getElementsByClassName('myForm');
console.log(myForm);

The console will log:

HTMLCollection { 0: form.myForm, length: 1 }

If you have just a single element with a unique class name, you should prefer document.querySelector over document.getElementsByClassName.

It's syntax will be:

let myForm = document.querySelector('.myForm'); // note the "." before the class name
console.log(myForm);

The output in the console will be:

<form class="myForm">

You can also attach an HTML ID to it and use document.getElementByID.

@praveenreddy1798
@umamaheswari.v

Collapse
 
venkat121998 profile image
venkat anirudh

Got it, thank you Habdul 😊

Thread Thread
 
ziizium profile image
Habdul Hazeez • Edited
Collapse
 
developertharun profile image
Tharun Shiv

That's a great answer in detail. thank you🙂

Thread Thread
 
ziizium profile image
Habdul Hazeez

You are welcome. I am glad I could help.

Collapse
 
praveenreddy1798 profile image
praveenreddy1798

Thank you @Habdul 😊

Collapse
 
uma_bcc profile image
umamaheswari.v

I think it would still return an HTML Collection

Collapse
 
praveenreddy1798 profile image
praveenreddy1798

Yeah, even I've the same doubt

Collapse
 
chandrika56 profile image
Jaya chandrika reddy

Great Article, will we also get to know about querySelector in this series?

Collapse
 
developertharun profile image
Tharun Shiv

Yes, they're coming up😊

Collapse
 
fortranjohn profile image
Temitope A Ogunbiyi

Great lesson Tharun

Collapse
 
developertharun profile image
Tharun Shiv

Thank you 🙂

Collapse
 
ducaale profile image
Mohamed Dahir

Do you plan on introducing querySelector and querySelectorAll for getting DOM elements? And maybe how to alias them to $ and $$ respectively?

Collapse
 
developertharun profile image
Tharun Shiv

Hi Mohamed,
Yes, they are definitely included as a part of this series. 😊 Thank you for showing interest