Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get element by class name

I want to know if there is a way to getElementByClassName("classname").innerHTML function or something to the equivalent of getElementById("ClassName").innerHTML.

like image 377
foshoeiyyy Avatar asked Dec 16 '11 18:12

foshoeiyyy


People also ask

How do you find an element with a specific class name?

Use the element. classList. contains() method to check if an element contains a specific class name.

How do you get element by class?

Document.getElementsByClassName() 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 name(s).


1 Answers

You are missing an s in your function name. getElementsByTagName returns a collection of elements, of elements, which you need to iterate over:

var elements = document.getElementsByClassName("classname");

for (var i = 0; i < elements.length; i++) {
    elements[i].innerHTML = 'foo';
}

IE8 and below don't support getElementsByClassName, so you'll have to find a polyfill or use querySelectorAll (IE8).

like image 147
Blender Avatar answered Sep 23 '22 10:09

Blender