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
The getElementsByClassName() method returns a collection of elements with a specified class name(s). The getElementsByClassName() method returns an HTMLCollection.
The getElementsByClassName() method returns a collection of child elements with a given class name. The getElementsByClassName() method returns a NodeList object.
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.
getElementById() is used to access the DOM elements using their id and getElementsByClassName() is used to access element(s) using their class .
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With