Get all Attributes from a HTML element with Javascript/jQuery

后端 未结 17 1812
时光说笑
时光说笑 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: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 + ',';
      }
    });
    
    

    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 +'
    '; } });
    
    
    
    
    
    
    
    
    

提交回复
热议问题