DEV Community

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

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
 
praveenreddy1798 profile image
praveenreddy1798

Yeah, even I've the same doubt

Collapse
 
uma_bcc profile image
umamaheswari.v

I think it would still return an HTML Collection

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
 
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
 
venkat121998 profile image
venkat anirudh

Got it, thank you Habdul 😊

Thread Thread
 
ziizium profile image
Habdul Hazeez • Edited
Collapse
 
praveenreddy1798 profile image
praveenreddy1798

Thank you @Habdul 😊