loading...

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

Collapse
ziizium profile image
Habdul Hazeez

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 Author

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

Thank you @Habdul 😊