Yes, document.getElementsByClassName would still return an HTMLcollection if there is only one element with that class name.
document.getElementsByClassName
HTMLcollection
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.
document.querySelector
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.
document.getElementByID
@praveenreddy1798 @umamaheswari.v
That's a great answer in detail. thank you🙂
You are welcome. I am glad I could help.
Got it, thank you Habdul 😊
You are welcome.
Thank you @Habdul 😊
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Yes,
document.getElementsByClassName
would still return anHTMLcollection
if there is only one element with that class name.Take the following code snippet.
The console will log:
If you have just a single element with a unique class name, you should prefer
document.querySelector
overdocument.getElementsByClassName
.It's syntax will be:
The output in the console will be:
You can also attach an HTML ID to it and use
document.getElementByID
.@praveenreddy1798
@umamaheswari.v
That's a great answer in detail. thank you🙂
You are welcome. I am glad I could help.
Got it, thank you Habdul 😊
You are welcome.
@praveenreddy1798
@umamaheswari.v
Thank you @Habdul 😊