Javascript document.getElementsByClassName does not return all elements

I have the following javascript code (pure js, no libs), however when I run it, it returns only one element instead of two

function changeButtonStyles() { var actualButtons = document.getElementsByClassName("read-more"); for (var i = 0; i < actualButtons.length; i++) { actualButtons[i].parentNode.className = "basic"; actualButtons[i].className = "btn btn-xs btn-default"; } 

It should return two elements from the page so that I can change both of them, but it returns only one, or the loop only iterates through one. Why is this?

jsfiddle

+5
source share
1 answer

Try to select all elements by

 document.querySelectorAll(".read-more"); 

I am updating the script https://jsfiddle.net/rzdkr2gL/7/

And you can use the forEach method

 actualButtons.forEach(function (el) { el.parentNode.className = "basic"; el.className = "btn btn-xs btn-default"; }) 

or (recommended method)

 Array.prototype.forEach.call(actualButtons, function (el) { el.parentNode.className = "basic"; el.className = "btn btn-xs btn-default"; }) 

or

 NodeList.prototype.forEach.call(actualButtons, function (el) { el.parentNode.className = "basic"; el.className = "btn btn-xs btn-default"; }) 

The final code may look like https://jsfiddle.net/rzdkr2gL/8/

+3
source

Source: https://habr.com/ru/post/1259691/


All Articles