Search code examples
javascripthtmlwebhref

How to make an a href do its work when it's inside another class that triggers an event whenver clicked


The question above might not be clear enough, so I will give an example as well:

For example, I have the following html code:

<ul class="do-sth">
    <li>Line 1</li>
    <li>Some text. <a href="http://www.google.com">Line 2.</a> Other text</li>
</ul>

The do-sth class triggers some even whenver it got clicked. So when I click Line 2, it will trigger that do-sth event and at the same time transferring to the href link. This is NOT what I want. What I would like to have is that whenever I click Line 2, the do-sth is not triggered. How to do that?


Solution

  • <ul class="do-sth">
        <li>Line 1</li>
        <li>Some text. <a href="somewhere">Line2</a>. Other text</li>
    </ul>
    
    <script>
        // try using event.stopPropagation or event.cancelBubble = true for IE
        document.querySelector('a').addEventListener('click', function(e)
        {
            e.stopPropagation();
            // do-sth won't be triggered
        }, false);
    </script>