开发者

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> 开发者_JS百科tags. How could that happen?


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)."


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>


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜