Explanation for document.getElementsByClassName

Explanation for document.getElementsByClassName
0

#1

the documentation for document.getElementsByClassName says You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.
What does the statement mean?


#2

When you call document.getElementsByClassName, you’re searching the whole document. But if you use it to get an element, you can call the method on that element rather than the whole document and it will only search inside there.

<div class="myDiv">
   <p>Not my favorite paragraph</p>
   <p class="myFavorite">I love this paragraph!</p>
</div>
<p>This paragraph will be ignored</p>
var someDiv = document.getElementsByClassName('myDiv');
var myFavoriteParagraph = someDiv[0].getElementsByClassName('myFavorite');

Here, the first time we call getElemenstByClassName, it’s on the entire document. We ask it to find an element with the class name of “myDiv”. The next line, we call getElementsByClassName on the element we found the first time, and the browser will only return elements with the class name “myFavorite” if they’re inside of that first element.


#3

Just a few seconds too late :neutral_face: : example


#4

doesnt someDiv store an array? Therefore shoudnt the second statement be like this: someDiv[0].getElementByClassName("myFavorite") ?


#5

Ah, yes indeed. Good catch. I’m used to using getElementById.


#6

you might want to edit your answer again… :slight_smile:


#7

Oye vey. I woke up too early and have had too little coffee. At least @BenGitter got it right!


#8

no worries. just wanted to make sure people who read the answers in the future dont get confused. Thanks to you and @BenGitter.