-1

I am currently working on a project in Javascript.

I would like to know how to get the ID of a element with a click.

This is my code:

const cercleEl = document.querySelectorAll(".cercle");

cercleEl.forEach((element) => {
  const elementId = element.getAttribute("id");
});
document.addEventListener("click", cercleEl);
mousetail
  • 7,009
  • 4
  • 25
  • 45

3 Answers3

2

You can do it like this:

document.addEventListener('click', (ev)=>{
    console.log(ev.target.id)
});

ev.target is the element you click on. Thus, you can easily find it's id by using ev.target.id. There is no need to create a list of all elements ID's at the start.

mousetail
  • 7,009
  • 4
  • 25
  • 45
1

You can try like this. You need to add ,addEventListener to Particular elements in forEach loop

const cercleEl = document.querySelectorAll(".cercle");

cercleEl.forEach((element) => {
   element.addEventListener("click", function() {
    console.log(this.getAttribute("id"))

  });
});
<div class="cercle" id="a">
  <h1>hi</h1>
</div>


<div class="cercle" id="b">
  <h1>hello</h1>
</div>
Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46
0
 document.querySelectorAll('.circle').forEach(function(element) {
   element.addEventListener('click', () => {
     console.log(element.id);
   });
 });
Sjn19
  • 75
  • 4