按類名

document.getElementsByClassName('class-name')

將檢索

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

如果沒有現有元素包含給定的類,則將返回空集合。

例:

<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