getElementByClassName + classList.add does not work

Asked

Viewed 62 times

1

I am using bootstrap for a job, I have a class that repeats v'Many times, I would like to use getElementByClassName to take all the elements that has this class and use clasList.add to add one more class, changing the class of all objects.

<div class="conteiner">
    <div class="row">
      <div class="border"> <!-- div que quero adicionar a classe -->
        <h1>Ola Mundo</h1>
      </div>
    </div>
  </div>



<script>
    const elemento = document.getElementByClassName('border');
var renovavel = false;
  if (renovavel === true) {
    elemento.classList.add('border-dark');
  }
  else {
    elemento.classList.add('border-success');
  }

1 answer

1

"getElementByClassName" does not exist, has getElementsByClassName which returns an array of elements, so you need to iterate over these elements, using for or foreach for example.

I added an example with getElementsByClassNameand also demonstrating querySelector and querySelectorAll

// getElementsByClassName pega todos elmentos:
const elementos = document.getElementsByClassName('border');
Array.prototype.forEach.call(elementos, function(elemento) {
       elemento.classList.add('border-dark');
});

// querySelector pega só o primeiro
var elementosDiferente = document.querySelector(".border-diferente");
elementosDiferente.classList.add('border-red');


// querySelectorAll pega todos elementos:
var divs = document.querySelectorAll('.teste');
Array.prototype.forEach.call(divs, function(elemento) {
       elemento.classList.add('fundo');
});
.border-dark {
  border: solid 3px #000
 }
 
 .border-red {
  border: solid 3px red
 }
 
 .fundo {
    background-color: cyan
 }
<div class="conteiner">
    <div class="row">
      <div class="teste border">
        <h1>Ola Mundo 1</h1>
      </div>
      <div class="teste border-diferente">
        <h1>Ola Mundo 2</h1>
      </div>
      <div class="teste border">
        <h1>Ola Mundo 3</h1>
      </div>
      <div class="teste border-diferente">
        <h1>Ola Mundo 4</h1>
      </div>
    </div>
  </div>

More details in the documentation: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

Browser other questions tagged

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