使用 Javascript 获取 HTML 字符串的属性列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5745175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the list of attributes of a HTML string using Javascript
提问by Bruno
How can I get the list of attributes of an HTML string using Javascript? Here's my code so far.
如何使用 Javascript 获取 HTML 字符串的属性列表?到目前为止,这是我的代码。
function traverse_test(){
var root=document.getElementById('arbre0').childNodes;
for(var i=0;i<root.length;i++){
var lis = root[i];
if (lis =='[object HTMLUListElement]') {
for (var member in lis) {
if (typeof lis[member] == "string") {
var assertion = lis[member];
var resultat = assertion.search(/..Bookmarks/);
if (resultat != -1) {
output.innerHTML+= lis[member];
// Here I'd like to have the list of lis[member] attributes
for(var attr in lis[member].attributes) {
output.innerHTML+=lis[member].attributes[attr].name + "=\""+ lis[member].attributes[attr].value + "\"";
}
break;
}
}
}
}
}
}
回答by Matt Ball
Use the Node.attributes
property of a DOM element. Example:
使用Node.attributes
DOM 元素的属性。例子:
var foo = document.getElementById('foo'),
attrs = foo.attributes,
i = attrs.length,
attr;
while (i--)
{
attr = attrs[i];
console.log(attr.name + '="' + attr.value + '"');
}
回答by Tom Gullen
If you know the attributes to get the value you can do:
如果您知道获取值的属性,则可以执行以下操作:
var MyValue = document.getElementById("myimage").getAttribute("src")
In JavaScript to loop all attributes:
在 JavaScript 中循环所有属性:
var el = document.getElementById("someId");
var arr = [];
for (var i=0, attrs=el.attributes, l=attrs.length; i<l; i++){
arr.push(attrs.item(i).nodeName);
}
The above code was taken from this question
上面的代码取自这个问题
Jquery might be another option:
Jquery 可能是另一种选择:
回答by Lorenzo Gangi
Seems like all these answers point to how to get an attr list from a node but the question asks for attrs from an HTML string. Here is my 2cents.
似乎所有这些答案都指向如何从节点获取 attr 列表,但问题要求从 HTML 字符串获取 attr。这是我的 2cents。
//turn your string into a node and get your html strings NamedNodeMap
var temp = document.createElement("div");
temp.innerHTML = "<div attr-1 attr-2 attr-3 attr-4></div>";
temp = temp.firstElementChild.attributes;
//put the attributes in a an array
var list = Object.keys(temp).map( function( index ) { return temp[ index ] } );
console.log( list );
回答by k33g_org
[].slice
.apply(document.querySelector('something').attributes)
.forEach(function(item){
console.log(item, item.name, item.value);
});