1

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.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Sony ThePony
  • 315
  • 1
  • 2
  • 13

2 Answers2

1

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"/>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
0

You can map a node's attributes to an object using:

var obj = {};
Array.from(node.attributes).forEach(function (attr) {
  obj[attr.name] = attr.value;
});

In jQuery, you can do the mapping via .map():

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

What you'll end up with is a collection of objects that contain the attributes for each node.

You can then use .get() to access the attributes for an individual node.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367