I am trying to use JavaScript to get a clicked element\'s information.
Here is the jsFiddle.
And below is my code.
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.
Welcome to StackOverflow!
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
})
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);
});
}
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`
})
}