I try to replace some href attributes with the IDs of some DIVs.
I have a list with (e.g.) three links and without href values like:
<ul id="Downloads">
<li><a href="">Some content 1</a></li>
<li><a href="">Some content 2</a></li>
<li><a href="">Some content 3</a></li>
</ul>
I also have some DIVs on the same page with unique IDs in a container:
<div id="DownloadsContent">
<div id="221">Some content</div>
<div id="325">Some content</div>
<div id="124">Some content</div>
</div>
I want to get the IDs of the three DIVs and set them as href attributes to the three links like:
<li><a href="#221">Some content 1</a></li>
<li><a href="#325">Some content 2</a></li>
<li><a href="#124">Some content 3</a></li>
I tried it with the .map and .each function, but with my current attempt, I get links like <a href="221,325,124"></a> – so the href attribute is replaced with the whole string.
Here’s my approach:
var id = $('#DownloadsContent > div').map(function() { return this.id }).get();
$.each(id,function() {
$("#Downloads li a").attr('href', id);
});
You can use
attrmethod.http://jsfiddle.net/AG2LQ/