DOM Retrieving Elements By Class Name


Example

document.getElementsByClassName('class-name')

will retrieve

<a class="class-name">Any</a>
<b class="class-name">tag</b>
<div class="class-name an-extra-class">with that class.</div>

If no existing elements contain the given class, an empty collection will be returned.


Example:

<p class="my-class">I will be matched</p>
<p class="my-class another-class">So will I</p>
<p class="something-else">I won't</p>
var myClassElements = document.getElementByClassName('my-class');
console.log(myClassElements.length); // 2
var nonExistentClassElements = document.getElementByClassName('nope');
console.log(nonExistentClassElements.length); // 0