2

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.

C14L
  • 12,153
  • 4
  • 39
  • 52
Metxaniz
  • 51
  • 1
  • 1
  • 3
  • http://stackoverflow.com/questions/2728252/jquery-stoppropagation-bubble-down or you could use css to remove the pointer events for the p tags – Pete May 20 '16 at 11:05

3 Answers3

5

To select the parent element, use

event.target.parentName

If the event could happen on any element, and you want to look for a certain ancestor element on the event.target, you need to walk up the inheritance chain. Or use jquery, that has a method for that.

If your case is a simple as in the example, you could just

if (event.target.tagName == "DIV") return event.target;
if (event.target.parentName.tagName == "DIV") return event.target.parentName;
C14L
  • 12,153
  • 4
  • 39
  • 52
5
function myFunction(event) { 
alert(event.target.parentNode.nodeName);
}

try this

0
$('div').on('click', function(event) {
    alert(event.target.nodeName);
});

Simply, in this case, on the click of any div, an alert would appear with its nodeName.

The way you've done it, would mean that wherever you clicked on the whole document, it would grab that element as the target. So it might grab the p within the div, rather than the div itself.

Hazonko
  • 1,025
  • 1
  • 15
  • 30