mcgowan.b mcgowan.b - 3 months ago 45
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?



Try select all elements by method


I update fiddle

And you can use forEach method

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

or, function (el) {
    el.parentNode.className = "basic";
    el.className = "btn btn-xs btn-default";

Final code may be looks like