How to get the attribute availables of a HTML tag with JS?

For example the HTML tag ‘CANVAS’ has special atribbutes like width=”” and height=”” same as ‘INPUT’, ‘AUDIO’, etc..

Getting all the styles properties available of a HTML tag using the getComputedStyle() function is amazing, but I want something like “getComputedAttributes()”

So, how can I get their attributes to be simply showed in a console.log() ? Thanks.

  • What do you mean exactly by “attribute availables”?

    – 

Using native elem.attributes:


function getAttributes(element) {
  const attributes = element.attributes;
  const attributeList = [];

  for (let i = 0; i < attributes.length; i++) {
    const attributeName = attributes[i].name;
    const attributeValue = attributes[i].value;
    attributeList.push(`${attributeName}="${attributeValue}"`);
  }

  return attributeList.join(' ');
}

// Example
const myElement = document.getElementById('something');
const elementAttributes = getAttributes(myElement);
console.log(elementAttributes);


NOTE:

This is correct, though it should be noted that this will give the collection of attributes that are actually present on the element. It will not give entries for attributes that might be set. Just to be clear. – Pointy

I believe to get the list of all native valid attributes you would need a stored list or object you pull from.

Leave a Comment