js get element by class name code example

Example 1: javascript get element by class

var elementsArray = document.getElementsByClassName("someclassname");

Example 2: javascript get element by class

var elements = document.querySelector(".class");

Example 3: get element by class

var x = document.getElementsByClassName("example");
var i;
for (i = 0; i < x.length; i++) {
  x[i].style.backgroundColor = "red";
}

Example 4: get element by class name

var y = document.getElementsByClassName('foo');
var aNode = y[0];

Tags:

Misc Example