List Attributes of an HTML Element with JS

Asked

Viewed 205 times

2

Talk, you guys, all in peace?

I was looking for a solution on the Internet, but I didn’t find what I needed, nor did I understand a way to do it, if anyone can shed some light?

I would like to list the attributes of an element, using Jquery, for example this input:

<input type="text" name="input1" id="input1" class="class1">

And the way out would be:

object{
    type: "text",
    name: "input1",
    id: "input1",
    class: "class1"
}
  • 1

    @Augustovasques was exactly what I was looking for! Thank you so much!

2 answers

4


You can use the Element.attributes that gives you an eternal object with nodes where you can extract the key and value of each property.

An example would be like this:

const input = document.getElementById('input1');
const attributes = {};
for (let attr of input.attributes) {
  attributes[attr.name] = attr.value; 
}

console.log(attributes) // {type:"text",name:"input1",id:"input1",class:"class1"}
<input type="text" name="input1" id="input1" class="class1">

2

With jQuery you can extend the method function .attr() to return all attributes of an element:

(function(e){
   $.fn.attr = function(){
      if(!arguments.length){
         if(!this.length) return null;

         var obj = {};
         $.each(this[0].attributes, function(){
            if(this.specified) obj[this.name] = this.value;
         });
         return obj;
      }

      return e.apply(this, arguments);
   }
})($.fn.attr);

var atributos = $("#input1").attr();

console.log(atributos);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="input1" id="input1" class="class1">

  • 1

    I suggest using attrs, plural, is more semantic.

  • It would be a great idea too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.