Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

javascript - 使用Javascript / jQuery从HTML元素获取所有属性(Get all Attributes from a HTML element with Javascript/jQuery)

I want to put all attributes in a Html element into an array: like i have a jQuery Object, whichs html looks like this:

(我想将Html元素中的所有属性放到一个数组中:就像我有一个jQuery Object,它的html看起来像这样:)

<span name="test" message="test2"></span>

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.

(现在一种方法是使用此处描述的xml解析器,但是随后我需要知道如何获取对象的html代码。)

the other way is to make it with jquery, but how?

(另一种方法是使用jquery进行修改,但是怎么做呢?)

the number of attributes and the names are generic.

(属性的数量和名称是通用的。)

Thanks

(谢谢)

Btw: I can't access the element with document.getelementbyid or something similar.

(顺便说一句:我无法使用document.getelementbyid或类似的东西来访问元素。)

  ask by k0ni translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

(如果只需要DOM属性,则在元素本身上使用attributes节点列表可能会更简单:)

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

Note that this fills the array only with attribute names.

(请注意,这仅用属性名称填充数组。)

If you need the attribute value, you can use the nodeValue property:

(如果需要属性值,则可以使用nodeValue属性:)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...