3

Is it possible to get both the attribute name and the value of an element?

Basically i want to get the name and the values of all attributes of a single element, in order to write them into a Javascript Object like this:

obj {
  key: "value",
  another_key: "another_value",
}

1 Answer 1

4

Using jQuery you can get name and values of all attributes for specific element like that:

var obj = {}; // this object will hold key-value pairs of elem attributes
var attribs = $('#elem')[0].attributes;
for (var i = 0; i < attribs.length; i++) {
    obj[attribs[i].name] = attribs[i].value;
}

Remember to replace '#elem' with a valid selector for the element you want to get attributes from.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.