問題描述
我想將 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 解析器 here,但是我需要知道如何獲取我的對象的 html 代碼.
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 屬性,在元素本身上使用 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);
}
這篇關于使用 Javascript/jQuery 從 HTML 元素中獲取所有屬性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!