Ivan
Ivan

Reputation: 525

jQuery: find H2 id and append link with same id

I have the following code and I want for every H2 with id attribute I would create an anchor link. I can not get it to work properly...

<div id="mydiv">
    <h2 id="first">first</h2>
    <h2>second</h2>
    <h2 id="third">third</h2>
</div>

.sls {color: red;font-size: 12px;}

$('#mydiv')
.find('h2[id]')
.append(' <a href="http://www.test.com/page.html#'+ $('h2[id]')
.attr('id') +'" class="sls">Link</a>');

https://jsfiddle.net/ivanionut/1ohh2hws/

Thanks for your help.

Upvotes: 0

Views: 1459

Answers (2)

Sasang
Sasang

Reputation: 1281

In your append call you are using $('h2[id]).attr() this will get the attribute of the first element in the set found, so it will always get the id for the first h2. Update the code to use this in the append using a function, like so:

.append(function() {
    return '<a href="http://www.test.com/page.html#'+ $(this).attr('id') +'"class="sls">Link</a>'
});

https://jsfiddle.net/1ohh2hws/2/

Upvotes: 2

Badacadabra
Badacadabra

Reputation: 8507

Do you want something like this?

$('#mydiv').find('h2[id]').each(function () {
  $(this).append(' <a href="http://www.test.com/page.html#'+ $(this).attr('id') +'" class="sls">Link</a>');
});
.sls {
  color: red;
  font-size: 12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv">
	<h2 id="first">first</h2>
	<h2>second</h2>
	<h2 id="third">third</h2>
</div>

Upvotes: 2

Related Questions