开发者

jquery apply an attribute to only the first element?

I'm trying to set an a name to the first link with a specific class, but I'm kinda unsur开发者_JAVA百科e as to how to apply something to just the first one?

So, I'm trying to find the first div with the sample class and then wrap the text within the div.title with the :

<div class="sample">
<div class="title"><a name="thisone">title</a></div>
<p>blah blah</p>
</div>

<div class="sample">
<div class="title">title</div>
<p>blah blah</p>
</div>

<div class="sample">
<div class="title">title</div>
<p>blah blah</p>
</div>


This works for me:

$("div.sample:first div.title").contents().wrap("<a name='thisone'></a>");

It finds the first <div> with class sample. Inside it finds the divs with class title and wraps their contents in a link.


Will that <a> be there already? If so:

$('.sample:first .title a').attr('name', 'thisone');

If you don't have the <a> there to start with and want to wrap it in, use this:

$('.sample:first .title').wrap('<a name="thisone" />')

(live example)


You need something like:

$('a:first').attr('name', 'thisone');
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜