使用Javascript获取HTML字符串的属性列表

Bru*_*uno 5 html javascript html-lists

如何使用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;
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*all 12

使用Node.attributesDOM元素的属性.例:

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

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

演示:http://jsfiddle.net/mattball/j8AVq/


Lor*_*ngi 6

似乎所有这些答案都指向如何从节点获取 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 );
Run Code Online (Sandbox Code Playgroud)