Javascript document.getElementsByClassName不返回所有元素 [英] Javascript document.getElementsByClassName not returning all elements
本文介绍了Javascript document.getElementsByClassName不返回所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下javascript代码(纯js,没有libs),但是当它运行时它只返回一个元素而不是两个
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
document.querySelectorAll(".read-more");
我更新小提琴 https://jsfiddle.net/rzdkr2gL/7/
你可以使用 forEach
方法
actualButtons.forEach(function (el) {
el.parentNode.className = "basic";
el.className = "btn btn-xs btn-default";
})
或(推荐方式)
Array.prototype.forEach.call(actualButtons, function (el) {
el.parentNode.className = "basic";
el.className = "btn btn-xs btn-default";
})
或
NodeList.prototype.forEach.call(actualButtons, function (el) {
el.parentNode.className = "basic";
el.className = "btn btn-xs btn-default";
})
最终代码可能看起来像 https:// js fiddle.net/rzdkr2gL/8/
Final code may be looks like https://jsfiddle.net/rzdkr2gL/8/
这篇关于Javascript document.getElementsByClassName不返回所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文