Search code examples
javascripthtmlevent-handlingevent-bubbling

Event not Bubbling to Parent Element from Child Element


I read the article on https://javascript.info/bubbling-and-capturing about Bubbling.

According to the article, the following event on the article tag with id="article" should have bubbled to the <p id="para"></p>, inside which article is nested.

    let para = document.getElementById("para");
    let article = document.getElementById("article");

    /*
    article.addEventListener("click", () => {
        console.log("I'm an article tag!");
    });
    */
    para.addEventListener("click", () => {
        console.log("I'm a p tag!");
    });
        <p id="para">
            <article id="article">Click Me!</article>
        </p>

However, absolutely, nothing happens. The Event listener on article works just fine(when not commented out). Why?


Solution

  • Your HTML is invalid. An <article> can't be a child of a <p> - check out the rendered HTML:

    console.log(document.body.innerHTML);
    <p id="para">
      <article id="article">Click Me!</article>
    </p>

    As a result, the browser ends the <p id="para"> when the <article> tag begins - so they're no longer parent and child, but siblings.

    (The <p> tag can only contain phrasing content, which the <article> tag is not)

    Make sure your HTML passes validation first.

    If you used something else valid - like a <span> - it'd work:

    let para = document.getElementById("para");
    let article = document.querySelector("span");
    
    /*
    article.addEventListener("click", () => {
        console.log("I'm an article tag!");
    });
    */
    para.addEventListener("click", () => {
      console.log("I'm a p tag!");
    });
    <p id="para">
      <span id="article">Click Me!</span>
    </p>