Reputation:
I have to assign to many html href
attributes (a tag) the value of their respective id immediately following.
With my code, I just get a only value (the first).
Thanks so much.
Juri
$(".anchor").attr("href","#"+($(".anchor").closest("div").next("div").attr("id")));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<a class="anchor">Get anchor 1</a>
</div>
<div id="link1">
<p>A paragraph</p>
</div>
<div>
<a class="anchor">Get anchor 2</a>
</div>
<div id="link2">
<p>Another paragraph</p>
</div>
Upvotes: 1
Views: 1920
Reputation: 171679
You need the instance of the selected element. Can use attr(attrName, function)
to do it
$(".anchor").attr("href",function(){
return '#' + $(this).closest("div").next("div").attr("id");
});
Upvotes: 1
Reputation: 334
use jQuery each
OR any loop like for
, while
etc to iterate on all .anchor elements.
Upvotes: 0
Reputation: 5246
Iterate a loop through all the a tag having class anchor and use $(this).parent("div").next("div").attr("id"))
selector to get the link for the a tag.
Please check below snippet.
$(".anchor").each(function(){
$(this).attr("href","#"+($(this).parent("div").next("div").attr("id")));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><a class="anchor">Get anchor 1</a>
</div>
<div id="link1">
<p>A paragraph</p>
</div>
<div><a class="anchor">Get anchor 2</a>
</div>
<div id="link2">
<p>Another paragraph</p>
</div>
Upvotes: 0
Reputation: 21489
Jquery .attr()
with function in second parameter, iterate selected elements and change attribute of its. Also use .parent()
instead of .closest("div")
$(".anchor").attr("href", function(){
return "#"+$(this).parent().next("div").attr("id");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<a class="anchor">Get anchor 1</a>
</div>
<div id="link1">
<p>A paragraph</p>
</div>
<div>
<a class="anchor">Get anchor 2</a>
</div>
<div id="link2">
<p>Another paragraph</p>
</div>
Upvotes: 0