修改具有相同标记名称的所有元素

时间:2014-08-29 17:17:36

标签: javascript html

在jQuery中,只需添加$("div")即可选择标记名为<div>的所有元素。

假设我想在纯JavaScript中执行此操作,我会尝试输入:document.getElementsByTagName("div"),但这只返回一个元素列表。

您无法一次编辑这些元素,您必须按发生的顺序选择它们,如下所示:document.getElementsByTagName("div")[*occurrence*]
有没有办法一次选择所有这些元素并将它们存储在变量中?

感谢。

2 个答案:

答案 0 :(得分:3)

  

有没有办法一次选择所有这些元素并将它们存储在变量中?

getElementsByTagName(或querySelectorAll 如何做到这一点。

但不,DOM没有像jQuery那样定义作用于列表元素的函数。当然,你可以自己写一些。

function setValue(list, value) {
    var n;
    for (n = 0; n < list.length; ++n) {
         list[n].value = value;
    }
};
我怀疑,jQuery的基于集合的方法是其吸引力的重要组成部分。事实上,通过使用mutators和accessors封装元素集,它可以让你将事物链接在一起。当然,你也可以自己做:

function MyList(selector) {
    this.elements = document.querySelectorAll(selector);
}
MyList.prototype.setAttr = function(attr, value) {
    var n;
    for (n = 0; n < list.length; ++n) {
         this.elements[n].setAttribute(attr, value);
    }
    return this;
};
MyList.prototype.setHTML = function(html) {
    var n;
    for (n = 0; n < list.length; ++n) {
         this.elements[n].innerHTML = html;
    }
    return this;
};

// Usage
var list = new MyList("div");
list.setHTML("hi there").setAttr("data-foo", "bar");

当然,与jQuery的版本相比,这些都是非常原始的......

答案 1 :(得分:0)

我制作了一个JSFiddle,展示了如何使用for ... in循环来使用所有找到的div:

<强> HTML

<div>text1</div>
<div>text2</div>
<div>text4</div>
<div>text3</div>
<span id="orderOfOutput"></span>

<强>的JavaScript

var allDivs = document.getElementsByTagName('div');
for (var i in allDivs) {
    if (isNaN(i)) continue;//we only want the numbered indexes
    document.getElementById('orderOfOutput').innerHTML += '<span>Output div:' + allDivs[i].innerText + '</span><br />';
}

要将它们存储在变量中,只需用divSelection[i] = allDivs[i];

替换innerHTML行
相关问题