'How to get all attributes of DOM element? [duplicate]
How to copy all user defined attributes for a DOM element into an array? I Unsuccessfully tested to get ["type", "onClick",'value','id']
See the following code
Js
var obj=document.getElementById('input')/*.attributes*/,
array=[],
index=0;
for(array[index++] in obj);
console.log(array);
html
<input type='button' onClick="Start()" id='input' value="Start"/>
Solution 1:[1]
Get all Attributes from a HTML element with Javascript/jQuery
Using it with your JS, you get:
var obj=document.getElementById('input')/*.attributes*/,
arr=[],
index=0;
for (var i = 0, atts = obj.attributes, n = atts.length; i < n; i++){
arr.push(atts[i].nodeName);
}
console.log(arr);
Solution 2:[2]
The attributes are available on the attributes NamedNodeMap; you access each one with [] notation, and there's a length.
So:
var array = Array.prototype.map.call(
document.getElementById('input').attributes,
function(attr) {
// Use nodeName for the name, nodeValue for the value
return attr.nodeName;
});
snippet.log(array.join(", "));
<input type='button' onClick="Start()" id='input' value="Start"/>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="https://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
| Solution 2 | ptim |
