Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Stop parent event firing on child element click

I have a click event on li tag and then in that li i have another nested li.

When clicked on parent li everything works fine. But onclick nested or child li the parent li click event is fired.

I have used event.stopPropagation() method but it does not work in my case.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$("li").on("click",function() {
  console.log(this.firstChild.textContent)
})
$('#testUl > li').on('click', function(e) {
  e.stopPropagation();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<ul id="testUl">
  <li>
    <a href="#">Test A</a>
    <div class="innerUl">
      <ul>
        <li>Inner A</li>
        <li>Inner B</li>
        <li>Inner C</li>
      </ul>
    </div>
  </li>
</ul>

>Solution :

Without jQuery you can use event delegation and determine to act using Element.closest()

document.addEventListener(`click`, handle);

function handle(evt) {
  console.clear();
  
  if (!evt.target.closest(`.innerUl`) && evt.target.closest(`#testUl`)) {
      console.log(`You clicked (something within) the first li of ul#testUl`);
  }
}
<ul id="testUl">
  <li>
    <a href="#">Test A</a>
    <div class="innerUl">
      <ul>
        <li>Inner A</li>
        <li>Inner B</li>
        <li>Inner C</li>
      </ul>
    </div>
  </li>
</ul>

Same idea with jQuery

$("#testUl").on("click", evt => {
    console.clear();
    if (!evt.target.closest(`.innerUl`) && evt.target.closest(`#testUl`)) {
      console.log(`You clicked ${evt.target.outerHTML}`);
    }
  });
<script 
  src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>

<ul id="testUl">
  <li>
    <a href="#">Test A</a>
    <div class="innerUl">
      <ul>
        <li>Inner A</li>
        <li>Inner B</li>
        <li>Inner C</li>
      </ul>
    </div>
  </li>
</ul>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading