获取所有属性从使用Javascript / jQuery的一个HTML元素 [英] Get all Attributes from a HTML element with Javascript/jQuery
问题描述
我想提出一个HTML元素的所有属性到一个数组:
像我有一个jQuery对象,伟驰HTML如下:
I want to put all attributes in a Html element into an array: like i have a jQuery Object, whichs html looks like this:
<span name="test" message="test2"></span>
现在的一种方法是使用描述的XML解析器<一href=\"http://stackoverflow.com/questions/1705504/javascript-jquery-how-do-i-get-an-array-of-all-attributes-in-an-xml-element\">here,但后来我需要知道如何让我的对象的HTML code。
now one way is to use the xml parser described here, but then i need to know how to get the html code of my object.
的另一种方法是使用jQuery做,但是怎么样?
属性和名称的数量是通用
the other way is to make it with jquery, but how? the number of attributes and the names are generic.
感谢
顺便说一句:我无法通过document.getElementById或类似的东西访问元素
Btw: I can't access the element with document.getelementbyid or something similar.
推荐答案
如果你只是想在DOM属性,它可能是简单的使用元素上的属性
节点列表本身:
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);
}
这篇关于获取所有属性从使用Javascript / jQuery的一个HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!