How can I append to a

tag inside a span with

2019-02-23 19:32发布

问题:

jsFiddle

I'm trying to append some text to a heading that is in a span. But I don't know how to append to the actual heading, and not just the span.

Style:

h1 {font-size:250%;color:red;}

HTML:

<span class="note">
    <h1>
        some text
    </h1>
</span>

I run this:

$('.note:first-child').append("more text");

But the text gets appended after the heading tag, and therefore doesn't have the heading style applied to it. How can I append to the heading?

回答1:

http://jsfiddle.net/bTubp/2/

$('.note h1:first-child').append("more text");

for inserting inside the first h1 of every .note class

and

$('.note:first-child h1').append("more text");

for inserting inside text for h1 of first .note class

For first h1 of first .note

$('.note:first-child h1:first-child').append("more text");


回答2:

You need a space for your selector to do what you mean:

$('.note :first-child').append("more text");

or:

$('.note > :first-child').append("more text");

See DEMOs:

  • http://jsfiddle.net/bTubp/3/
  • http://jsfiddle.net/bTubp/4/

When you say: .note:first-child it means something with class note that is also the first child of its parent. When you say: .note :first-child it means something that is the first child of its parent and is inside (maybe deeply) of something with class note. When you say: .note>:first-child it means: something that is the first child of its parent and its parent has class note and this is probably what you meant.

I see that there are already a lot of answers before I finished writing it but I will still post it because I hope it explains why your selector didn't work.



回答3:

$('.note:first-child h1').append("more text");


回答4:

$(".note h1:first").append("more text");

This would look for the class ".note", followed by the first h1 tag.