Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

362
Views
¿Cómo puedo obtener un valor de índice de un div simplemente haciendo clic en él?

Estoy tratando de cambiar la clase de un div específico en el que hago clic, usando esto:

 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>

Este código anterior funciona bien, pero solo en todos los div al mismo tiempo, no solo con eso que hice clic

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

No hay necesidad de id s y no debe usar atributos de eventos en línea como onclick y, en su lugar, separe su JavaScript de su HTML y use el estándar .addEventListener() en su lugar.

Además, no es necesario Array.prototype.forEach() ya que .forEach es compatible con la lista de nodos devuelta por querySelectorAll() .

Para obtener el índice, simplemente use el parámetro de índice que expone .forEach() :

 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 Report

0

about 4 years ago · Juan Pablo Isaza Report

0

Podría pasar el ID de div a la función de prueba como

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

entonces su función de prueba podría verse así:

 function test(id){ let foundDiv = document.getElementById(d) foundDiv.classList.add('y'); foundDiv.classList.remove('x'); }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!