Manipulating Htmlcollection elements

Asked

Viewed 233 times

0

I wonder if with just javascript I can manipulate the elements of a Htmlcollection the same way I would with using jQuery selector.

For example take the result of document.getElementsByClassName('ativo') and add to all found elements the class 'greater'.

  • Yes, because jQuery is javascript (Javascript library)

1 answer

1


Of course, all you have to do is iterate over the result and add the desired class. See a simple example where I return the result with the for:

const itens = document.getElementsByClassName('ativo');

for (let item of itens) {
  item.classList.add("maior");
}
.maior {
  color: red;
}
<div class="ativo">Texto 1</div>
<div class="ativo">Texto 2</div>
<div class="ativo">Texto 3</div>
<div class="ativo">Texto 4</div>

Browser other questions tagged

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