How to Change this JS to Use GetElementsByClassName

- 1 answer

Ad

I am attempting to make this JS add a class to another class (not an id):

 var d = document.getElementById("div1");
 d.className = d.className + " other class";

ie.

  var d = document.getElementsByClassName("div1");
  d.className = d.className + " other class";

I have a pen here that you can toy with: http://codepen.io/xkurohatox/pen/wMWKKM

Ideally it would be nice for something that functions with IE 8+ and modern browsers. JAVASCRIPT ONLY PLEASE (No JQuery please).

Any suggestions? Thanks!

Ad

Answer

Ad

document.getElements.className actually returns a collection instead of a single value.

You need to access individual elements by using array-bracket notation.

var d = document.getElementsByClassName("gold")[0]'

The above gets the first element with the required class name.

Here's a demonstration

var gold = document.getElementsByClassName("gold");

for (var i = 0; i < gold.length; i++) {
	gold[i].classList.add("bold");
}
.gold { background: gold; }
.bold { font-weight: bold; }
<p class="gold">Paragraph 1</p>
<p>Paragraph 2</p>

<p class="gold">Paragraph 3</p>

Ad
source: stackoverflow.com
Ad