Document.getElementsByClassName and elements with more than one class

Asked

Viewed 614 times

2

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>

I can take this element this way?

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

And if I do element.className = "class"; this will erase all classes that this element had or will add a?

And to add is using +=, correct?

  • 2

    works yes...

  • And if I do element.classname = "class"; this will erase all the classes that that element had or will add one?

  • 1

    It will replace everything. but if you want to add.

  • to add is using += right?

  • 1

    That’s right, I recommend using this site https://fiddle.jshell.net/, is great for simple testing of this type

  • 1

    Thanks for your attention, you really helped.

Show 1 more comment

1 answer

0


The getElementbyclassname will fetch 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
  • notes that getElementbyclassname has E big (in 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 the .className = ... but it is necessary to bear in mind that classes are separated by spaces. So el.className += 'nova-classe' will undesired effect as it will stick with the old class, it has to be += ' nova-classe' (Look at the space ' nova-....

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

To:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.