Search code examples
javascriptjqueryhtmlattributeshref

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>


Solution

  • 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>