Jquery apply attribute only to first element?

I'm trying to set a name for the first link with a specific class, but I'm not sure how to apply something only to the first?

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

<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>
+2
source share
3 answers

This works for me:

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

He finds the first <div>with the class sample. Inside, it finds divs with the class titleand wraps their contents by reference.

+2
source

Will it <a>be there already? If yes:

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

If you don’t have <a>one to start with and want to wrap it up, use this:

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

(live example)

0
source

You need something like:

$('a:first').attr('name', 'thisone');
-2
source

Source: https://habr.com/ru/post/1733299/


All Articles