baDrosa82
baDrosa82

Reputation: 137

JS get the clicked element with event.target

I am trying to use JavaScript to get a clicked element's information. Below is my code.

let div = document.querySelector('div')
div.addEventListener('click', function(event) {
  // how to get the clicked p tag here?
  // this?
  // event.target.currentTarget?
})
<div>
  <p>text 1</p>
  <p>text 2</p>
</div>

How can I use this to get the element's information?

Upvotes: 6

Views: 19082

Answers (4)

itamar
itamar

Reputation: 3967

e.target should give you the exact element that was clicked to generate the event.

e.currentTarget will give you the element that the event is at when the function was called (after bubbling up from the e.target)

div.addEventListener('click', (e) => {
console.log(e.target) // the p that was clicked
console.log(e.currentTarget) // this div
})

Upvotes: 9

Matt Croak
Matt Croak

Reputation: 2888

If you use event.target you should get the specific p tag that you clicked.

However, if you really want to use this, you're better off attaching the onclick event handler to the p tags themselves rather than the parent.

Like so.

let ps = document.getElementsByTagName('p')

for (var i = 0; i < ps.length; ++i){
    ps[i].addEventListener('click', function(event){
        // how to get the clicked p tag here?
        alert(this.innerText) //or whatever action you want to do with `this`
   })
}

Upvotes: 0

dw_
dw_

Reputation: 1827

Probably best to attach the event listener to each of the p elements in case you have other children elements nested within the p element itself.

const paragraphs = document.querySelectorAll("div > p");

for (let i = 0; i < paragraphs.length; i += 1) {
  paragraphs[i].addEventListener("click", function (event) {
        console.log(event.currentTarget);
  });
}

Upvotes: 0

dome2k
dome2k

Reputation: 867

As I wrote in my comment event.target should be fine. But you should be careful if you really only want the p-tags. If you use a-tags or other child elements in the wrapping div you could potentially also receive other tags.

I'd suggest to actually add the event listener to the p-tags directly.

Upvotes: 1

Related Questions