How to Get Element By Class in JavaScript and change aria-checked="false" to "true"?

Mike Muller picture Mike Muller · Jan 4, 2013 · Viewed 9k times · Source

I am trying to select multiple classes on a page and change the aria-checked="false" to aria-checked="true". Here is the script I am using now:

elms=document.getElementsByClassName("d-va-p a-f-e");
for (i=0;i<elms.length;i++){
    if(elms[i].getAttribute("aria-checked")="false")
        elms[i].getAttribute("aria-checked")="true"
};

The source code is below. The class is "d-va-p a-f-e".

<div class="d-va-p a-f-e" style="-webkit-user-select: none;" role="option" tabindex="-1" aria-checked="false" id=":89">
    <div class="a-f-e" style="-webkit-user-select: none;">
        <div class="d-va-p-Fe a-f-e" style="-webkit-user-select: none;">
            <img src="https://lh4.googleusercontent.com/-FxDBvNDkbj4/AAAAAAAAAAI/AAAAAAAAAAA/q4f7Fc7OF6A/s48-c/photo.jpg" class="d-va-p-Z a-f-e">
        </div>
        <div class="a-f-e d-va-p-yda" style="-webkit-user-select: none;">
            <div class="d-va-p-Ec a-f-e" style="-webkit-user-select: none;">Herb Smith</div>
        </div>
    </div>
    <div class="d-va-p-iI-oc" style="-webkit-user-select: none;">
        <span class="a-f-e d-J-Eb-v-YA-Me" style="-webkit-user-select: none;"></span>
    </div>
</div>

Answer

bfavaretto picture bfavaretto · Jan 4, 2013

I see two problems. First, you're using assignment instead of comparison. So

if(elms[i].getAttribute("aria-checked")="false")

should be:

if(elms[i].getAttribute("aria-checked")=="false")

Second, your attempt to set the attribute's value won't work. Try this:

elms[i].setAttribute("aria-checked", true);