简体   繁体   中英

Modify an element's class inside another element in Javascript

So my HTML snippet looks something like this:

<div class="accordion-heading ">
    <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" target="_self" href="#item-name">
        <b class=""> Items ({{vm.selectedItems.length}})</b>
        <i class='fa fa-chevron-down'></i>
    </a>
</div

So when it is expanded the HTML changes to look something like :

<div class="accordion-heading ">
    <a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion2" target="_self" href="#item-name">
        <b class=""> Items ({{vm.selectedItems.length}})</b>
        <i class='fa fa-chevron-up'></i>
    </a>
</div>

What I want is based on some condition if the chevron-up class is applied, I want to remove the same and apply chevron-down class.

var element = document.getElementsByClassName("fa fa-chevron-up")[0];
element.classList.remove("fa-chevron-up").add("fa-chevron-down");

But this does not function properly. Because once we remove the class it says can not add class to undefined .

How to achieve the same?

Element.classList.remove does not return the class list, so you can't do method chaining. You have to do it like this:

var element = document.getElementsByClassName("fa fa-chevron-up")[0];
element.classList.remove("fa-chevron-up");
element.classList.add("fa-chevron-down");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM