JS get the clicked element with event.target

前端 未结 4 558
青春惊慌失措
青春惊慌失措 2021-01-28 13:17

I am trying to use JavaScript to get a clicked element\'s information.

Here is the jsFiddle.

And below is my code.

4条回答
  •  忘掉有多难
    2021-01-28 13:49

    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);
      });
    }
    

提交回复
热议问题