Prevent javascript onclick on child element

I just had the same issue and could not get jQuery to work so I used simple Javascript:

document.getElementById("your_span").addEventListener("click", (event) => {
    event.stopPropagation();
});

That did the trick for me. Obviously you need to add the addEventListener to every Element you wanna apply this to. Since I do a lot of DOM manipulation this was not an issue for me. Hope this helps anyone :)


Give the span an id an attach onclick event to it and use

A jQuery sample

$("#spn2").click(function(event){
  event.stopPropagation();  
});

event.stopPropagation(): Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.


It would make sense to use a library but without you can try this (edited with an entire page to test):

<html><head></head>
<body>
<script type="text/javascript"><!--
function manualToggle(val)
{
    alert(val.id);
}

--></script>

<div id="test" onclick="manualToggle(this);">
    <span>Allowed to click</span>
    <span onclick="event.cancelBubble=true;if (event.stopPropagation) event.stopPropagation();">Not allowed to click</span>
    <span>Allowed to click</span>
</div>
</body>
</html>

You need an event handler (it's very easy to do this in something like jQuery) that catches clicks for the spans within the div and only fires the function if, for example, the span has/hasn't a particular class.