1

I'm thinking for develop a web component form, so... I was wondering my self if it's possible read attributes from a html elements. For example:

<my-component input="3" data-input='"name", "address", "email"' textarea="1" data-textarea='"mensaje"'></my-component>

<script>
while i <= elementattributes.length{
elementattributes[i] 
} 
</script>

I know that I can access through .getAttribute, but this way will take more code... I just want to be something smart :P

Sorry, my english is poor... I hope you can understand what I want to do :P :)

3 Answers 3

1

If you want to get all of the attributes and their values, you can do something like this:

function getElementAttrs(el) {
  var attributes = [].slice.call(el.attributes);
  return attributes.map(function(attr) {
    return {
      name: attr.name,
      value: attr.value
    }
  });
}

var allAttrs = getElementAttrs(document.querySelector('my-component'));

console.log(allAttrs);
<my-component input="3" data-input='name,address,email' textarea="1" data-textarea='"mensaje"'></my-component>

The function getElementAttrs returns an array of objects to you with attribute name-value pairs as keys on the object so that you can loop over it, or just pull by key.

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

Comments

1

You can use dataset to get specific data attribute

var data = document.querySelector('my-component').dataset.input.split(',');
data.forEach(function(e) {
 console.log(e)
})
<my-component input="3" data-input='name,address,email' textarea="1" data-textarea='"mensaje"'></my-component>

If you want to return all attributes from element you can use attributes which return array-like object, but you can create object with name-value from that

var data = document.querySelector('my-component').attributes, attr = {};
Array.from(data).forEach(function(e) {
  attr[e.name] = e.value;
});

console.log(attr['data-input']);
<my-component input="3" data-input='name,address,email' textarea="1" data-textarea='mensaje'></my-component>

1 Comment

I think the OP is wanting to get all of the attributes and their values, not just data- attribute values
0

You can just use .attributes:

document.getElementById("ELEMENT_ID").attributes

This will return an object containing each attribute with its associated value. You can then index the attributes array for specific attributes and use .value for it's corresponding value.

1 Comment

Wow... jajajaja it's so simple... i never imagined got all attributes with the method .attributes :P This is just what I need :). Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.