Metxaniz Metxaniz - 6 months ago 23
jQuery Question

Event.target. Select the parent instead the child

I would like to know if there is any chance of selecting only the parent div instead its child. An easy example would be this:

<!DOCTYPE html>
<html>
<body onclick="myFunction(event)">
<div style="border: solid black 2px">

<p>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>
</div>
<script>
function myFunction(event) {
alert(event.target.nodeName);
}
</script>
</body>
</html>


What I want is simple, I want to click in the div, (does not mind if it is on the p labels) and recieve the msg that div has been clicked.
By now if I click on p labels I am getting p msg.

The fact is that I am trying to select the div instead the p label only, for example to change all its color. Thank you all.

Answer
function myFunction(event) { 
alert(event.target.parentNode.nodeName);
}

try this

Comments