The getElementsByClassName Method
About
The getElementsByClassName
is defined on document
and on HTMLElement
objects. It takes a string of space-separated class names and returns a list of elements which have all the classes specified in the string.
When it is called as a method of document
, this method returns all elements in the DOM which bear the classes specified. When it is called on an HTMLElement
, this method returns only those elements which both bear the classes and are children of that element.
Usage
For example, suppose we have the following elements in our DOM.
<div id="container"> <span class="a b f"></span> <span class="b c f"></span> <span class="c d f"></span> </div> <span class="d e f"></span>
One Class
Since every span in this document has the class "f", if we call getElementsByTagName
in the following way, it will return a list of all four spans.
var result = document.getElementsByTagName("f"); /* result.length == 4 */
However, if we instead call it on the container div, it will only return the three spans which are its children.
var result = document.getElementById("container").getElementsByTagName("f"); /* result.length == 3 */
Multiple Classes
Passing multiple classes as arguments returns the intersection of elements which bear them. For example:
var result = document.getElementsByTagName("b"); /* result.length == 2 because the first two spans have class b. */ result = document.getElementsByTagName("b c"); /* result.length == 1 because the only the second span has both */ /* class b and class c. */
Demo
Enter a string argument to be passed into the getElementsByClassName
function and see how many elements are returned. Recall that the argument is a space-separated string of classes.
Source Code
The HTML source code for the input and display in the previous section is below.
<ul> <li> <label for="classInput">Classes:</label> <input type="text" id="classInput" value="a" /> <input type="button" id="goButton" value="Go!" /> </li> <li> <label>Result Length:</label> <span id="resultLength"></span> </li> </ul>
The JavaScript source code to do the actual computation is below.
document.getElementById("goButton").onclick = function() { var doc = document.getElementById("exampleHidden"), expr = document.getElementById("classInput").value, result = doc.getElementsByClassName(expr).length; document.getElementById("resultLength").innerText = result; };
References
- http://www.w3.org/TR/html5/dom.html
#dom-document-getelementsbyclassname - https://developer.mozilla.org/en/DOM/
document.getElementsByClassName