Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript document.getElementsByClassName not returning all elements [duplicate]

Tags:

javascript

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

like image 746
Colonel Mustard Avatar asked Nov 13 '16 19:11

Colonel Mustard


People also ask

What does the JS getElementsByClassName () return?

The getElementsByClassName() method returns a collection of elements with a specified class name(s). The getElementsByClassName() method returns an HTMLCollection.

Does getElementsByClassName return NodeList?

The getElementsByClassName() method returns a collection of child elements with a given class name. The getElementsByClassName() method returns a NodeList object.

What does getElementsByClassName return if not found?

getElementbyId will return an Element object or null if no element with the ID is found. getElementsByClassName will return a live HTMLCollection, possibly of length 0 if no matching elements are found.

What is the difference between getElementById and getElementsByClassName?

getElementById() is used to access the DOM elements using their id and getElementsByClassName() is used to access element(s) using their class .


1 Answers

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 (recommended way)

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";
})

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

like image 121
Dmitrii Korchemkin Avatar answered Oct 29 '22 11:10

Dmitrii Korchemkin