Get the list of attributes of a HTML string using Javascript

ⅰ亾dé卋堺 提交于 2019-12-05 10:09:00

Use the Node.attributes property of a DOM element. Example:

var foo = document.getElementById('foo'),
    attrs = foo.attributes,
    i = attrs.length,
    attr;

while (i--)
{
    attr = attrs[i];
    console.log(attr.name + '="' + attr.value + '"');
}

Demo: http://jsfiddle.net/mattball/j8AVq/

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:

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:

http://plugins.jquery.com/project/getAttributes

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.

//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 );
[].slice
.apply(document.querySelector('something').attributes)
.forEach(function(item){
    console.log(item, item.name, item.value);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!