Get all Attributes from a HTML element with Javascript/jQuery

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

    Roland Bouman's answer is the best, simple Vanilla way. I noticed some attempts at jQ plugs, but they just didn't seem "full" enough to me, so I made my own. The only setback so far has been inability to access dynamically added attrs without directly calling elm.attr('dynamicAttr'). However, this will return all natural attributes of a jQuery element object.

    Plugin uses simple jQuery style calling:

    $(elm).getAttrs();
    // OR
    $.getAttrs(elm);
    

    You can also add a second string param for getting just one specific attr. This isn't really needed for one element selection, as jQuery already provides $(elm).attr('name'), however, my version of a plugin allows for multiple returns. So, for instance, a call like

    $.getAttrs('*', 'class');
    

    Will result in an array [] return of objects {}. Each object will look like:

    { class: 'classes names', elm: $(elm), index: i } // index is $(elm).index()
    

    Plugin

    ;;(function($) {
        $.getAttrs || ($.extend({
            getAttrs: function() {
                var a = arguments,
                    d, b;
                if (a.length)
                    for (x in a) switch (typeof a[x]) {
                        case "object":
                            a[x] instanceof jQuery && (b = a[x]);
                            break;
                        case "string":
                            b ? d || (d = a[x]) : b = $(a[x])
                    }
                if (b instanceof jQuery) {
                    var e = [];
                    if (1 == b.length) {
                        for (var f = 0, g = b[0].attributes, h = g.length; f < h; f++) a = g[f], e[a.name] = a.value;
                        b.data("attrList", e);
                        d && "all" != d && (e = b.attr(d))
                    } else d && "all" != d ? b.each(function(a) {
                        a = {
                            elm: $(this),
                            index: $(this).index()
                        };
                        a[d] = $(this).attr(d);
                        e.push(a)
                    }) : b.each(function(a) {
                        $elmRet = [];
                        for (var b = 0, d = this.attributes, f = d.length; b < f; b++) a = d[b], $elmRet[a.name] = a.value;
                        e.push({
                            elm: $(this),
                            index: $(this).index(),
                            attrs: $elmRet
                        });
                        $(this).data("attrList", e)
                    });
                    return e
                }
                return "Error: Cannot find Selector"
            }
        }), $.fn.extend({
            getAttrs: function() {
                var a = [$(this)];
                if (arguments.length)
                    for (x in arguments) a.push(arguments[x]);
                return $.getAttrs.apply($, a)
            }
        }))
    })(jQuery);
    

    Complied

    ;;(function(c){c.getAttrs||(c.extend({getAttrs:function(){var a=arguments,d,b;if(a.length)for(x in a)switch(typeof a[x]){case "object":a[x]instanceof jQuery&&(b=a[x]);break;case "string":b?d||(d=a[x]):b=c(a[x])}if(b instanceof jQuery){if(1==b.length){for(var e=[],f=0,g=b[0].attributes,h=g.length;f<h;f++)a=g[f],e[a.name]=a.value;b.data("attrList",e);d&&"all"!=d&&(e=b.attr(d));for(x in e)e.length++}else e=[],d&&"all"!=d?b.each(function(a){a={elm:c(this),index:c(this).index()};a[d]=c(this).attr(d);e.push(a)}):b.each(function(a){$elmRet=[];for(var b=0,d=this.attributes,f=d.length;b<f;b++)a=d[b],$elmRet[a.name]=a.value;e.push({elm:c(this),index:c(this).index(),attrs:$elmRet});c(this).data("attrList",e);for(x in $elmRet)$elmRet.length++});return e}return"Error: Cannot find Selector"}}),c.fn.extend({getAttrs:function(){var a=[c(this)];if(arguments.length)for(x in arguments)a.push(arguments[x]);return c.getAttrs.apply(c,a)}}))})(jQuery);
    

    jsFiddle

    /*  BEGIN PLUGIN  */
    ;;(function($) {
    	$.getAttrs || ($.extend({
    		getAttrs: function() {
    			var a = arguments,
    				c, b;
    			if (a.length)
    				for (x in a) switch (typeof a[x]) {
    					case "object":
    						a[x] instanceof f && (b = a[x]);
    						break;
    					case "string":
    						b ? c || (c = a[x]) : b = $(a[x])
    				}
    			if (b instanceof f) {
    				if (1 == b.length) {
    					for (var d = [], e = 0, g = b[0].attributes, h = g.length; e < h; e++) a = g[e], d[a.name] = a.value;
    					b.data("attrList", d);
    					c && "all" != c && (d = b.attr(c));
    					for (x in d) d.length++
    				} else d = [], c && "all" != c ? b.each(function(a) {
    					a = {
    						elm: $(this),
    						index: $(this).index()
    					};
    					a[c] = $(this).attr(c);
    					d.push(a)
    				}) : b.each(function(a) {
    					$elmRet = [];
    					for (var b = 0, c = this.attributes, e = c.length; b < e; b++) a = c[b], $elmRet[a.name] = a.value;
    					d.push({
    						elm: $(this),
    						index: $(this).index(),
    						attrs: $elmRet
    					});
    					$(this).data("attrList", d);
    					for (x in $elmRet) $elmRet.length++
    				});
    				return d
    			}
    			return "Error: Cannot find Selector"
    		}
    	}), $.fn.extend({
    		getAttrs: function() {
    			var a = [$(this)];
    			if (arguments.length)
    				for (x in arguments) a.push(arguments[x]);
    			return $.getAttrs.apply($, a)
    		}
    	}))
    })(jQuery);
    /*  END PLUGIN  */
    /*--------------------*/
    $('#bob').attr('bob', 'bill');
    console.log($('#bob'))
    console.log(new Array(50).join(' -'));
    console.log($('#bob').getAttrs('id'));
    console.log(new Array(50).join(' -'));
    console.log($.getAttrs('#bob'));
    console.log(new Array(50).join(' -'));
    console.log($.getAttrs('#bob', 'name'));
    console.log(new Array(50).join(' -'));
    console.log($.getAttrs('*', 'class'));
    console.log(new Array(50).join(' -'));
    console.log($.getAttrs('p'));
    console.log(new Array(50).join(' -'));
    console.log($('#bob').getAttrs('all'));
    console.log($('*').getAttrs('all'));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    All of below is just for stuff for plugin to test on. See developer console for more details.
    <hr />
    <div id="bob" class="wmd-button-bar"><ul id="wmd-button-row-27865269" class="wmd-button-row" style="display:none;">
    <div class="post-text" itemprop="text">
    <p>Roland Bouman's answer is the best, simple Vanilla way. I noticed some attempts at jQ plugs, but they just didn't seem "full" enough to me, so I made my own. The only setback so far has been inability to access dynamically added attrs without directly calling <code>elm.attr('dynamicAttr')</code>. However, this will return all natural attributes of a jQuery element object.</p>
    
    <p>Plugin uses simple jQuery style calling:</p>
    
    <pre class="default prettyprint prettyprinted"><code><span class="pln">$</span><span class="pun">(</span><span class="pln">elm</span><span class="pun">).</span><span class="pln">getAttrs</span><span class="pun">();</span><span class="pln">
    </span><span class="com">// OR</span><span class="pln">
    $</span><span class="pun">.</span><span class="pln">getAttrs</span><span class="pun">(</span><span class="pln">elm</span><span class="pun">);</span></code></pre>
    
    <p>You can also add a second string param for getting just one specific attr. This isn't really needed for one element selection, as jQuery already provides <code>$(elm).attr('name')</code>, however, my version of a plugin allows for multiple returns. So, for instance, a call like</p>
    
    <pre class="default prettyprint prettyprinted"><code><span class="pln">$</span><span class="pun">.</span><span class="pln">getAttrs</span><span class="pun">(</span><span class="str">'*'</span><span class="pun">,</span><span class="pln"> </span><span class="str">'class'</span><span class="pun">);</span></code></pre>
    
    <p>Will result in an array <code>[]</code> return of objects <code>{}</code>. Each object will look like:</p>
    
    <pre class="default prettyprint prettyprinted"><code><span class="pun">{</span><span class="pln"> </span><span class="kwd">class</span><span class="pun">:</span><span class="pln"> </span><span class="str">'classes names'</span><span class="pun">,</span><span class="pln"> elm</span><span class="pun">:</span><span class="pln"> $</span><span class="pun">(</span><span class="pln">elm</span><span class="pun">),</span><span class="pln"> index</span><span class="pun">:</span><span class="pln"> i </span><span class="pun">}</span><span class="pln"> </span><span class="com">// index is $(elm).index()</span></code></pre>
        </div>
      </div>

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

    Try something like this

        <div id=foo [href]="url" class (click)="alert('hello')" data-hello=world></div>
    

    and then get all attributes

        const foo = document.getElementById('foo');
        // or if you have a jQuery object
        // const foo = $('#foo')[0];
    
        function getAttributes(el) {
            const attrObj = {};
            if(!el.hasAttributes()) return attrObj;
            for (const attr of el.attributes)
                attrObj[attr.name] = attr.value;
            return attrObj
        }
    
        // {"id":"foo","[href]":"url","class":"","(click)":"alert('hello')","data-hello":"world"}
        console.log(getAttributes(foo));
    

    for array of attributes use

        // ["id","[href]","class","(click)","data-hello"]
        Object.keys(getAttributes(foo))
    
    0 讨论(0)
  • 2020-11-22 05:53

    Imagine you've got an HTML element like below:

    <a class="toc-item"
       href="/books/n/ukhta2333/s5/"
       id="book-link-29"
    >
       Chapter 5. Conclusions and recommendations
    </a>
    

    One way you can get all attributes of it is to convert them into an array:

    const el = document.getElementById("book-link-29")
    const attrArray = Array.from(el.attributes)
    
    // Now you can iterate all the attributes and do whatever you need.
    const attributes = attrArray.reduce((attrs, attr) => {
        attrs !== '' && (attrs += ' ')
        attrs += `${attr.nodeName}="${attr.nodeValue}"`
        return attrs
    }, '')
    console.log(attributes)
    

    And below is the string that what you'll get (from the example), which includes all attributes:

    class="toc-item" href="/books/n/ukhta2333/s5/" id="book-link-29"
    
    0 讨论(0)
  • 2020-11-22 05:53

    Attributes to Object conversion

    *Requires: lodash

    function getAttributes(element, parseJson=false){
        let results = {}
        for (let i = 0, n = element.attributes.length; i < n; i++){
            let key = element.attributes[i].nodeName.replace('-', '.')
            let value = element.attributes[i].nodeValue
            if(parseJson){
                try{
                    if(_.isString(value))
                    value = JSON.parse(value)
                } catch(e) {}
            }
            _.set(results, key, value)
        }
        return results
    }
    

    This will convert all html attributes to a nested object

    Example HTML: <div custom-nested-path1="value1" custom-nested-path2="value2"></div>

    Result: {custom:{nested:{path1:"value1",path2:"value2"}}}

    If parseJson is set to true json values will be converted to objects

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

    Does this help?

    This property returns all the attributes of an element into an array for you. Here is an example.

    window.addEventListener('load', function() {
      var result = document.getElementById('result');
      var spanAttributes = document.getElementsByTagName('span')[0].attributes;
      for (var i = 0; i != spanAttributes.length; i++) {
        result.innerHTML += spanAttributes[i].value + ',';
      }
    });
    <span name="test" message="test2"></span>
    <div id="result"></div>

    To get the attributes of many elements and organize them, I suggest making an array of all the elements that you want to loop through and then create a sub array for all the attributes of each element looped through.

    This is an example of a script that will loop through the collected elements and print out two attributes. This script assumes that there will always be two attributes but you can easily fix this with further mapping.

    window.addEventListener('load',function(){
      /*
      collect all the elements you want the attributes
      for into the variable "elementsToTrack"
      */ 
      var elementsToTrack = $('body span, body div');
      //variable to store all attributes for each element
      var attributes = [];
      //gather all attributes of selected elements
      for(var i = 0; i != elementsToTrack.length; i++){
        var currentAttr = elementsToTrack[i].attributes;
        attributes.push(currentAttr);
      }
      
      //print out all the attrbute names and values
      var result = document.getElementById('result');
      for(var i = 0; i != attributes.length; i++){
        result.innerHTML += attributes[i][0].name + ', ' + attributes[i][0].value + ' | ' + attributes[i][1].name + ', ' + attributes[i][1].value +'<br>';  
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <span name="test" message="test2"></span>
    <span name="test" message="test2"></span>
    <span name="test" message="test2"></span>
    <span name="test" message="test2"></span>
    <span name="test" message="test2"></span>
    <span name="test" message="test2"></span>
    <span name="test" message="test2"></span>
    <div name="test" message="test2"></div>
    <div name="test" message="test2"></div>
    <div name="test" message="test2"></div>
    <div name="test" message="test2"></div>
    <div id="result"></div>

    0 讨论(0)
提交回复
热议问题