0

This is the code:

<!DOCTYPE html>
<html>
<body onclick="myFunction(event)">

<p onclick="myFunction(event)">Click on a paragraph. An alert box will alert the element that triggered the event.</p>

<p><strong>Note:</strong> The target property returns the element that triggered the event, and not necessarily the eventlistener's element.</p>

<script>
function myFunction(event) { 
    alert(event.target.nodeName);
}
</script>

</body>
</html>

So when I click on <p>, there are two pop-up windows which are all regarding to P, but shouldn't we have one P and one Body as onclick event is associated with <body> tag?

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Read [What is event bubbling and capturing?](https://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing) and http://javascript.info/bubbling-and-capturing – Satpal May 27 '17 at 13:01

1 Answers1

1

You code working correct .Its showing target element tag name .Its right because you not clicking empty body .its have some children element That was p so its showing the p .it only show the clicked text of element tag name .simply add a text not contain any element direct text of the body.

function myFunction(event) { 
    alert(event.target.nodeName);
}
<body onclick="myFunction(event)">
its direct text of the body click here you get the body
<p onclick="myFunction(event)">Click on a paragraph. An alert box will alert the element that triggered the event.</p>

<p><strong>Note:</strong> The target property returns the element that triggered the event, and not necessarily the eventlistener's element.</p>


</body>
prasanth
  • 22,145
  • 4
  • 29
  • 53