Search code examples
jqueryhtmlattributeshref

jQuery code to set unique href attributes within list items


I have a list of 200 items. Each <li> contains an <h3> tag with text string of a unique phone number. Each <li> also contains <a> tag, parent of the <h3>. On page load, I need to set the href value of each <a> tag with the phone number contained within it's child <h3>.

jQuery

$("a").each(function() {
    var phonenumber = $(this > "h3").html();
    $(this).attr("href", "phonenumber");
});

HTML

<li>
    <h1>Altman, Jennifer, Phd</h1>
    <a href="">
        <h3>617-999-5054</h3>
    </a>
</li>

Solution

  • You have to use .find() as shown:

    $("a").each(function() {
       var phonenumber = $(this).find("h3").text();
       $(this).attr("href", phonenumber);
    });
    

    Fiddle