document.getElementsByClassName and elements with more than one class

1

When an element has more than one class it works if you 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 this way?

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

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

And to add is using += , correct?

    
asked by anonymous 13.08.2017 / 02:13

1 answer

0

The getElementbyclassname will fetch all elements that have a given class and return a collection of elements. Important details:

  • The method returns a collection, not an array.

To have an array you must 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
  • Even though an element has more / other classes it will fetch this element as long as it has the class it is looking for

To add a class to an element you can use getElementbyclassname but you have to take into account that classes are separated by spaces. Then E will undesirable effect because it will paste with the old class, it must be e (repair in .className = ... space.

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

To:

  • add: el.className += 'nova-classe'
  • remove: += ' nova-classe'
13.08.2017 / 08:43