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>
Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
sibi
  • 585
  • 3
  • 7
  • 23
  • 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 Jan 23 '19 at 09:34

1 Answers1

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>
Roko C. Buljan
  • 180,066
  • 36
  • 283
  • 292