How to add class with pure javascript (no jQuery)

Asked

Viewed 73 times

0

I would like to know how to do that when the second element from the first ul receive the class ". active" the class image ". img2" receive a class of type "active-image" with pure javascript. Please.

Important: It is not enough to select only the element that has the class . active, but its order. Type: Select element 3 if it has class . active.

<ul>
  <li><a href="#">home</a></li>
  <li><a href="#">about</a></li>
  <li><a href="#">service</a></li>
</ul>

<ul>
  <li><img class="img1" src="#"/></li>
  <li><img class="img2" src="#"/></li>
  <li><img class="img3" src="#"/></li>
</ul>

  • And what is the condition for the element to receive the class active? You already have that part of the code?

  • if the second element has the class . active, for example. I don’t know any javascript. rs

2 answers

2

See if this helps you:

const itens = [...document.querySelectorAll('#menu li')];

const imagens = [...document.querySelectorAll('#imagens img')];

itens.forEach(i => {

  i.addEventListener('click', ev => selecionar(ev));

});

const selecionar = (ev) => {

  const t = ev.currentTarget;
  
  itens.forEach(i => i.classList.remove('active'));
  
  imagens.forEach(i => i.classList.remove('imagem-ativa'));
  
  t.classList.add('active');

  imagens[itens.indexOf(t)].classList.add('imagem-ativa');

};
ul#menu li.active {
text-transform: uppercase;}

.imagem-ativa {border: 2px solid red;}
<ul id="menu">
  <li><a href="#">home</a></li>
  <li><a href="#">about</a></li>
  <li><a href="#">service</a></li>
</ul>

<ul id="imagens">
  <li><img class="img1" src="#"/></li>
  <li><img class="img2" src="#"/></li>
  <li><img class="img3" src="#"/></li>
</ul>

0

In pure Javascript you can change the class as follows:

var elementos = document.getElementsByClassName("img2");
elementos[0].classList.add("imagem-ativa");

Browser other questions tagged

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