Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the list of attributes of a HTML string using Javascript

How can I get the list of attributes of an HTML string using Javascript? Here's my code so far.

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;
                    }
                }
            }
        }
    }
}
like image 627
Bruno Avatar asked Apr 21 '11 14:04

Bruno


People also ask

How can we fetch all attributes for an HTML element in JavaScript?

To get all of the attributes of a DOM element: Use the getAttributeNames() method to get an array of the element's attribute names. Use the reduce() method to iterate over the array. On each iteration, add a new key/value pair containing the name and value of the attribute.

How do I get attributes in HTML?

HTML DOM getAttribute() method is used to get the value of the attribute of the element. By specifying the name of the attribute, it can get the value of that element. To get the values from non-standard attributes, we can use the getAttribute() method.


2 Answers

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/

like image 113
Matt Ball Avatar answered Oct 27 '22 05:10

Matt Ball


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 );
like image 24
Lorenzo Gangi Avatar answered Oct 27 '22 04:10

Lorenzo Gangi