user6382106
user6382106

Reputation:

How to set id of next element into href attribute of link using jquery?

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

Answers (4)

charlietfl
charlietfl

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

Developer
Developer

Reputation: 334

use jQuery each OR any loop like for, while etc to iterate on all .anchor elements.

Upvotes: 0

Rahul Patel
Rahul Patel

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

Mohammad
Mohammad

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

Related Questions