且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Javascript/jQuery 从 HTML 元素中获取所有属性

更新时间:2023-02-19 17:08:03

如果你只想要 DOM 属性,在元素本身上使用 attributes 节点列表可能更简单:

If you just want the DOM attributes, it's probably simpler to use the attributes node list on the element itself:

var el = document.getElementById("someId");
for (var i = 0, atts = el.attributes, n = atts.length, arr = []; i < n; i++){
    arr.push(atts[i].nodeName);
}

请注意,这只会用属性名称填充数组.如果需要属性值,可以使用 nodeValue 属性:

Note that this fills the array only with attribute names. If you need the attribute value, you can use the nodeValue property:

var nodes=[], values=[];
for (var att, i = 0, atts = el.attributes, n = atts.length; i < n; i++){
    att = atts[i];
    nodes.push(att.nodeName);
    values.push(att.nodeValue);
}