get all attributes of an html element using javascript-ThrowExceptions

Exception or error:

How can I get all attributes of an HTML element?
For example I have an element:

<input type="text" class"cls1" id="myId" name="myName"/> 

and I want to see all attributes/properties that can be used for this input and not only attribute assigned already (type, class, id, name) on but all available attributes that can be used on this element.

With this method I can see only assigned attributes 😐

var attr = document.getElementById("myId").attributes;
console.log(attr);
How to solve:
var el = document.getElementById("myId");

var nodes=[], values=[];
for (var att, i = 0, atts = el.attributes, n = atts.length; i < n; i++){
    att = atts[i];
    nodes.push(att.nodeName);
    values.push(att.nodeValue);
    console.log(att.nodeName + " - " + att.nodeValue);
}

###

You can do this,

var attr = document.getElementById("myId").attributes;
for (var key in attr) {
  if (typeof attr[key] != 'function')
    console.log(attr[key]);
}

###

Try console.dir().

console.dir(document.getElementById('myId'));

###

var attr = document.getElementById("myId").attributes;
for (var key in attr) {
    var element = attr[key];
    if (typeof element === "object") {
        console.log(element.name);
        console.log(element.value);
    }
}

###

I think you can get all the enumerable properties using

var el = document.getElementById("myId");
var props = Object.keys(el); //will return an array of properties

Demo: Fiddle

Object.Keys() – For older browsers use a polyfill

Leave a Reply

Your email address will not be published. Required fields are marked *