Home > Software design >  Event not Bubbling to Parent Element from Child Element
Event not Bubbling to Parent Element from Child Element

Time:11-17

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related