mcgowan.b mcgowan.b - 27 days ago 9
Javascript Question

Javascript document.getElementsByClassName not returning all elements

I have the following javascript code (pure js, no libs), however when its run it only returns 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 I can modify them both, but it only returns the one or the loop only iterates through one. Why is this?

jsfiddle

Answer

Try select all elements by method

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

I update fiddle https://jsfiddle.net/rzdkr2gL/7/

And you can use forEach method

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

or

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

Final code may be looks like https://jsfiddle.net/rzdkr2gL/8/