Get all Attributes from a HTML element with Javascript/jQuery

后端 未结 17 1984
时光说笑
时光说笑 2020-11-22 05:07

I want to put all attributes in a Html element into an array: like i have a jQuery Object, whichs html looks like this:



        
17条回答
  •  时光取名叫无心
    2020-11-22 05:40

    Much more concise ways to do it:

    Old way (IE9+):

    var element = document.querySelector(/* … */);
    [].slice.call(element.attributes).map(function (attr) { return attr.nodeName; });
    

    ES6 way (Edge 12+):

    [...document.querySelector(/* … */).attributes].map(attr => attr.nodeName);
    
    • document.querySelector() returns the first Element within the document that matches the specified selector.
    • Element.attributes returns a NamedNodeMap object containing the assigned attributes of the corresponding HTML element.
    • [].map() creates a new array with the results of calling a provided function on every element in the calling array.

    Demo:

    console.log(
      [...document.querySelector('img').attributes].map(attr => attr.nodeName)
    );
    /* Output console formatting */
    .as-console-wrapper { position: absolute; top: 0; }
    …

提交回复
热议问题