javascript – document.getElementsByClassName and elements with more than one class

Question:

When an element has more than one class does it work if I use document.getElementsByClassName passing only one of the classes?

If I have an element like:

<div class="class1 class2 class3 ..."></div>

Can I get this element that way?

document.getElementByClassname("class1")[i];

And if I make element.className = "class"; Will it delete all the classes that element had or will it add one?

And to add is using += , correct?

Answer:

getElementbyclassname fetches all elements that have a given class and returns a collection of elements. Important details:

  • the method returns a collection, not an array.

To have an array you have to convert with:

var arr = [].slice.call(colecao); // compativel com JavaScript antigo
var arr = Array.from(colecao); // ES5 (não suportado no IE)
var arr = [...colecao]; // ES6
  • notice that getElementbyclassname has E large (in the question you had e small)

  • even if an element has more/other classes it will fetch that element as long as it has the class it is looking for


To add a class to an element you can use .className = ... but you must bear in mind that the classes are separated by spaces. So el.className += 'nova-classe' will be undesired as it will paste with the old class, it has to be += ' nova-classe' (notice the space ' nova-... .

But the best way is to use the new ES5 method, the .classList API .

For:

  • add: el.classList.add('nova-classe', 'mais-outra', etc...)
  • remove: el.classList.remove('minha-classe')
Scroll to Top