Home >Web Front-end >JS Tutorial >How Can I Get All HTML Element Attributes with JavaScript/jQuery?

How Can I Get All HTML Element Attributes with JavaScript/jQuery?

Barbara Streisand
Barbara StreisandOriginal
2024-11-26 13:33:10499browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn