Get all Attributes from a HTML element with Javascript/jQuery

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

    In javascript:

    var attributes;
    var spans = document.getElementsByTagName("span");
    for(var s in spans){
      if (spans[s].getAttribute('name') === 'test') {
         attributes = spans[s].attributes;
         break;
      }
    }
    

    To access the attributes names and values:

    attributes[0].nodeName
    attributes[0].nodeValue
    
    0 讨论(0)
  • 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);
    <span name="test" message="test2"></span>

    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"]
    
    0 讨论(0)
  • 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; }
    <img src="…" alt="…" height="…" width="…"/>

    0 讨论(0)
  • 2020-11-22 05:43

    Every answer here is missing the simplest solution using the getAttributeNames element method!

    It retrieves the names of all the element's current attributes as a regular Array, that you can then reduce to a nice object of keys/values.

    const getAllAttributes = el => el
      .getAttributeNames()
      .reduce((obj, name) => ({
        ...obj,
        [name]: el.getAttribute(name)
      }), {})
    
    console.log(getAllAttributes(document.querySelector('div')))
    <div title="hello" className="foo" data-foo="bar"></div>

    0 讨论(0)
  • 2020-11-22 05:45

    Because in IE7 elem.attributes lists all possible attributes, not only the present ones, we have to test the attribute value. This plugin works in all major browsers:

    (function($) {
        $.fn.getAttributes = function () {
            var elem = this, 
                attr = {};
    
            if(elem && elem.length) $.each(elem.get(0).attributes, function(v,n) { 
                n = n.nodeName||n.name;
                v = elem.attr(n); // relay on $.fn.attr, it makes some filtering and checks
                if(v != undefined && v !== false) attr[n] = v
            })
    
            return attr
        }
    })(jQuery);
    

    Usage:

    var attribs = $('#some_id').getAttributes();
    
    0 讨论(0)
  • 2020-11-22 05:47
    Element.prototype.getA = function (a) {
            if (a) {
                return this.getAttribute(a);
            } else {
                var o = {};
                for(let a of this.attributes){
                    o[a.name]=a.value;
                }
                return o;
            }
        }
    

    having <div id="mydiv" a='1' b='2'>...</div> can use

    mydiv.getA() // {id:"mydiv",a:'1',b:'2'}
    
    0 讨论(0)
提交回复
热议问题