pmiranda
pmiranda

Reputation: 8420

javascript, can't change class on all elements of the same class

I need to remove all the classes from an i html element. I have a table with many elements per row. They are:

<i class="fa fa-trash fa-fw"></i>

I want to change them due a condition, through javascript, like this:

<script>
    if(1){//doesn't matter what 'if' is, it's working this part
        document.getElementsByClassName('fa-trash').className = '';
    }
</script>

But nothing happends. When I use getElementById it works, but I don't want to use id, because I have many elements. What I'm doing wrong?

Upvotes: 1

Views: 234

Answers (1)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

getElementsByClassName method returns a collection as a NodeList object. The NodeList object represents a collection of nodes. So you need to update className for every item from the query result. For this, you can use Array.from method.

The Array.from() method creates a new Array instance from an array-like or iterable object.

Array.from(document.getElementsByClassName('fa-trash')).forEach(function(item){
    item.className = '';
});

Upvotes: 3

Related Questions