joshlsullivan
joshlsullivan

Reputation: 1500

Changing list items in javascript

I am trying to change the list items in an entire document. I'm using the following code, but I get an error. What am I doing wrong?

function changeListItems() {
var listItem = document.getElementsByTagName("ul");
var docItem = listItem.getElementsByTagName("li");
docItem.setAttribute("class", "list-group-item");
};
changeListItems();

Fiddle

Upvotes: 0

Views: 94

Answers (2)

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

Because document.getElementsByTagName() Returns an HTMLCollection of elements with the given tag name.

you should loop through each element and add class to it.

For Ex:

var docItem = listItem.getElementsByTagName("li");

for(var i=0; i< docItem.length; i++)
{
  docItem[i].className = "list-group-item"
}

Upvotes: 5

Barmar
Barmar

Reputation: 781004

getElementsByTagName return a NodeList, you have to iterate over it.

Since you have two levels of tags, you'd have to write nested loops. But it's simpler to get all the list items at once with querySelectorAll.

function changeListItems() {
    var docItem = document.querySelectorAll("ul li");
    for (var i = 0; i < docItem.length; i++) {
        docItem[i].setAttribute("class", "list-group-item");
    }
}

Upvotes: 2

Related Questions