0

I am getting a element ref by below code and I want add a class and remove a class from all the elements which i get.

app.component.html

<ul>
   <li class="option-btn cm-grey" />option 1</li>
   <li class="option-btn cm-grey" />option 1</li>
   <li class="option-btn cm-grey" />option 1</li>
</ul>

app.component.ts

var allbtn = document.querySelectorAll('.option-btn');
allbtn.removeClass('cm-grey');
allbtn.addClass('cm-blue');

Above code is not working.

James Z
  • 12,209
  • 10
  • 24
  • 44
AMit SiNgh
  • 325
  • 4
  • 17

1 Answers1

1

Please use classlist

allbtn.classList.add("mystyle");

Note: The classList property is not supported in Internet Explorer 9. The following code will work in all browsers:

function myFunction() {
    var element, name, arr;
    element = document.getElementById("myDIV");
    name = "mystyle";
    arr = element.className.split(" ");
    if (arr.indexOf(name) == -1) {
        element.className += " " + name;
    }
}

Similarly

allbtn.classList.remove("mystyle");

Cross-browser solution

function myFunction() {
    var element = document.getElementById("myDIV");
    element.className = element.className.replace(/\bmystyle\b/g, "");
}

You can further pass class names to these functions as a parameter if you want to go for cross-browser support (which I encourage) and make these functions reusable.

Gurmeet Singh
  • 774
  • 8
  • 21