Sony ThePony Sony ThePony - 3 months ago 6
jQuery Question

jQuery, get tag attributes and assign them to a variable

How do I add the attributes of a tag to a variable so I can insert them elsewhere?

So an input tag should assign a variable:

tags = { 'type' : 'submit' , 'id' : 'submit' };


I know you can ADD attributes using
.attr()
, but something like

testMe = $("#submit").attr();


Does not work.

Answer

You could get all attributes by looping through element.attributes like :

$.each(document.getElementById("submit").attributes, function() {
    tags[this.name] = this.value;
});

Hope this helps.

var tags = {};

$.each(document.getElementById("submit").attributes, function() {
    tags[this.name] = this.value;
});

console.log(tags);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" value="Submit" id="submit"/>