Home >Web Front-end >JS Tutorial >How Can I Get All HTML Element Attributes with JavaScript/jQuery?
Getting All Attributes from a HTML Element with JavaScript/jQuery
The goal of this question is to retrieve all attributes from a given HTML element and store them in an array. The element is not accessible through known methods like getElementById.
Using DOM Attributes
The simplest approach to obtain DOM attributes is to utilize the attributes node list of the element itself:
var el = document.getElementById("someId"); for (var i = 0, atts = el.attributes, n = atts.length, arr = []; i < n; i++){ arr.push(atts[i].nodeName); }
This approach only retrieves the attribute names.
Using NodeValue
To obtain both the attribute name and value, use the nodeValue property:
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); }
The above is the detailed content of How Can I Get All HTML Element Attributes with JavaScript/jQuery?. For more information, please follow other related articles on the PHP Chinese website!