Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

363
Visualizações
How can i get a index value of a div just clicking on it?

I'm trying to change the class of an specific div that i click, using this:

let divs = document.querySelectorAll('.x');

function idk(){
  Array.prototype.forEach.call(divs, function(element) {
    element.classList.add('y');
    Array.prototype.forEach.call(divs, function(element) {
      element.classList.remove('x');  
    });
  });
}
.y{
   transition: 0.5s;
   transform: rotateY(180deg);
}
<div id="d1">
   <div id="c1" class="x" onclick="idk()">a</div>
   <div id="c2" class="x" onclick="idk()">b</div>
   <div id="c3" class="x" onclick="idk()">c</div>
</div>

This code above works well, but only in all divs at the same time, not with only that I've clicked

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

There is no need for id s and you should not use inline event attributes like onclick and instead separate your JavaScript from your HTML and use the standard .addEventListener() instead.

Also, Array.prototype.forEach() is not needed since .forEach is compatible with the list of nodes returned by querySelectorAll() .

To get the index, simply use the index parameter that .forEach() exposes:

 document.querySelectorAll(".x").forEach(function(element, index){ element.addEventListener("click", function(event){ console.log(index); }); });
 <div class="x">a</div> <div class="x">b</div> <div class="x">c</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

about 4 years ago · Juan Pablo Isaza Relatório

0

You could pass in the div ID to the test function like

<div id="c3" class="x" onclick="idk('c3')"></div>

then your test function could look like:

function test(id){
  let foundDiv = document.getElementById(d)
  foundDiv.classList.add('y');
  foundDiv.classList.remove('x');
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda