jqueryfunctionlabeleach

Get text and use for aria-label on each


I want to get the text from each a.parent_link and apply it as an aria-label on each corresponding toggle button (button.sub-expand_collapse). The final result I want is if aria-expanded = true add aria-label= close + (text) and if aria-expanded = false add aria-label= expand + (text).

The first part gives me the text

$(".togSubList").each(function () {
        var bob = $(this).find(".parent_link").text();
        console.log(bob);
    });

But I can't get each one to add a the aria-label.

     $(".togSubList").each(function () {
        var bob = $(this).find(".parent_link").text();
        //console.log(bob);
        $(".sub-expand_collapse").each(function(){
            $(this).attr("aria-label","expand " + bob)
        }); 
    });

HTML

   <li class="sub_p01 togSubList">

        <button class="sub-expand_collapse" aria-expanded="false">
            <i class="fa fa-plus" aria-hidden="true"></i>
        </button>

        <a id="subLnk_01" class="parent_link menu_p01" href="m01_c01_p01.html"><strong>Space saving widgets</strong></a> 
        <ul aria-labelledby="subLnk_01" class="sub_items">
            list of links
        </ul>
    </li>

Solution

  • You Don't need second each function because inside LI you have only one element so just use node traverse . and find the element like this . and apply the attribute .

    $(".togSubList").each(function () {
            var bob = $(this).find(".parent_link").text();
    
            $(this).find(".sub-expand_collapse[aria-expanded='false']").attr("aria-label","expand " + bob);
             $(this).find(".sub-expand_collapse[aria-expanded='true']").attr("aria-label","close " + bob);
                
    
        });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <li class="sub_p01 togSubList">
    
            <button class="sub-expand_collapse" aria-expanded="false">
                <i class="fa fa-plus" aria-hidden="true"></i>
            </button>
    
            <a id="subLnk_01" class="parent_link menu_p01" href="m01_c01_p01.html"><strong>Space saving widgets</strong></a> 
            <ul aria-labelledby="subLnk_01" class="sub_items">
                list of links
            </ul>
        </li>