开发者

jquery apply an attribute to only the first element?

开发者 https://www.devze.com 2022-12-20 23:38 出处:网络
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?

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

精彩评论

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