Kitty
Kitty

Reputation: 29

How to access a `<div>` tag inside a `<p>` tag?

$("p div").click(function() {
  $(this).css({
    "color": "#F00",
    "font": "bold 20px verdana",
    "background-color": "#0FF"
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>Hello<div> World!</div></p>

Nothing happens when I click the “World” text, and when I inspect the elements, it says:

<p>Hello</p>
<div> World</div>
<p></p>

Notice those <p> tags. How could that happen?

Upvotes: 1

Views: 1098

Answers (4)

user113716
user113716

Reputation: 322492

The browser is kicking the <div> out of the <p> because it isn't a valid placement, so you won't be able to select it there.

Browsers often do try to make corrections for invalid HTML, but the result isn't necessarily predictable, so you'll need to use valid HTML instead.


http://www.w3.org/TR/html401/struct/text.html#h-9.3.1

"The P element represents a paragraph. It cannot contain block-level elements (including P itself)."

Upvotes: 4

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

It is not valid for a div to appear within a p. That's why Firefox has re-arranged your [broken] HTML, and you can see its "fixed" result through Firebug. Use a span instead.

Also, don't forget to put this event handler setup inside an onLoad handler, because your p and span don't necessarily exist when your script initially runs:

$(function() {
    $('p span').click(function(){
        $(this).css({
            'color':            '#F00',
            'font':             'bold 20px verdana',
            'background-color': '#0FF'
        });
    });
});

Live demo.

Upvotes: 0

James Hill
James Hill

Reputation: 61802

The browser will not respect your placement of a div inside a p. Change it to a span. Here's a working Fiddle.

Upvotes: 0

Michael Lorton
Michael Lorton

Reputation: 44386

That's interesting. The problem is that your browser is working correctly, and I hate when that happens. P is an in-line tag and DIV is a block tag (that is, it represents a rectangular area of the screen, as opposed to a possibly-irregular section of text like a in-line tag could) and there's a rule that you cannot put a block tag inside an in-line tag, so that's how your browser solved it.

EDIT: I notice @magicmike suggested a good solution:

<p>Hello<span> World!</span></p>

Upvotes: 0

Related Questions