Explanation for document.getElementsByClassName

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?

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 Likes

Just a few seconds too late :neutral_face: : example

2 Likes

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

1 Like

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

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

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

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

1 Like