0

I am trying to understand event bubbling, while try with my own code: `

<!DOCTYPE html>
    <html>
       <body>
          <div onclick="alert('1')">
             1
             <div onclick="alert('2')">
                2
                <div onclick="alert('3')">3</div>
             </div>
          </div>
       </body>
    </html>

Here I saw that, when click div 3, it shows three alert (3 2 1). After I change the first div tag to P tag, I click that same div 3 it come up with only two alert (3 2). Here, why alert 1 is not coming since it is under the parent(P) tag.

After change first div tag to P tag, code looks like below:

<p onclick="alert('1')">
  1
  <div onclick="alert('2')">
    2
    <div onclick="alert('3')">3</div>
  </div>
</p>

1
  • 1
    div elements cannot be placed in p elements. Inspect the code interpreted by the browser in your second snippet; you'll see that the two div elements are broken out.
    – BenM
    Commented Jan 23, 2019 at 9:34

1 Answer 1

1

Simply because the browser will fix your mistake in layering yout HTML markup.
The closing </p> tag is inserted where appropriate (before the block-level DIV) since <div> is not an allowed descendant of <p>.

The resulting markup is:

<p onclick="alert('1')">
  1
</p>
<div onclick="alert('2')">
  2
  <div onclick="alert('3')">3</div>
</div>
<p></p>

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.