Get all Attributes from a HTML element with Javascript/jQuery

后端 未结 17 2011
时光说笑
时光说笑 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:38

    This approach works well if you need to get all the attributes with name and value in objects returned in an array.

    Example output:

    [
        {
            name: 'message',
            value: 'test2'
        }
        ...
    ]
    

    function getElementAttrs(el) {
      return [].slice.call(el.attributes).map((attr) => {
        return {
          name: attr.name,
          value: attr.value
        }
      });
    }
    
    var allAttrs = getElementAttrs(document.querySelector('span'));
    console.log(allAttrs);

    If you want only an array of attribute names for that element, you can just map the results:

    var onlyAttrNames = allAttrs.map(attr => attr.name);
    console.log(onlyAttrNames); // ["name", "message"]
    

提交回复
热议问题