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?
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?
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:
Elarge (in the question you had
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 .
el.classList.add('nova-classe', 'mais-outra', etc...)