Laurence L
Laurence L

Reputation: 623

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>

Upvotes: 2

Views: 23596

Answers (2)

JYoThI
JYoThI

Reputation: 12085

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>

Upvotes: 3

partypete25
partypete25

Reputation: 4413

Because you are already looping through each ".togSubList" you dont need to loop through each toggle button within that. Just use "this" as a reference and target both accordingly.

The only problem is that you will need to re-run the function whenever the button is expanded/collapsed.

$(".togSubList").each(function () {
    var bob = $(this).find(".parent_link").text();
    //console.log(bob);
    $(".sub-expand_collapse[aria-expanded='false']", this).attr("aria-label","expand " + bob);
    $(".sub-expand_collapse[aria-expanded='true']", this).attr("aria-label”,”close " + bob);        
});

Upvotes: 0

Related Questions