在 JavaScript 中使用 getAttribute() 获取 HTML 元素的属性
在 JavaScript 中使用 attributes 属性获取 HTML 元素的属性
在 JavaScript 中使用 jQuery 获取 HTML 元素的属性
本教程指导如何使用 JavaScript 和 jQuery 获取 HTML 元素的属性。
我们将使用带有 querySelector() 和 getElementById() 方法的 getAttribute() 函数,以及 attributes 节点列表来获取属性名称及其值。
getAttribute() 方法输出元素属性的值;该元素可以通过标签或 ID 选择。
我们使用 querySelector 选择标签元素;它给出了文档中与选择器匹配的第一个元素,而 getElementById() 获取具有指定 id 的第一个元素。
attributes 属性返回特定 HTML 元素的属性集合。
在 JavaScript 中使用 getAttribute() 获取 HTML 元素的属性
让我们从 HTML 文档对象模型 (DOM) 的 getAttribute() 函数开始获取指定 HTML 元素的属性值。
示例代码:
This is a paragraph
const getElementByID = document.getElementById("getAttr")
const getElementByQuery = document.querySelector('p');
console.log(getElementByID.getAttribute("name"));
console.log(getElementByQuery.getAttribute("id"));
输出:
"attr"
"testP"
在 JavaScript 中使用 attributes 属性获取 HTML 元素的属性
在下面的代码中,我们使用 attributes 属性来访问特定 HTML 元素的属性名称和值,并使用 push() 方法将它们插入到两个单独的数组中。
你可以在此处找到有关 push() 函数的更多信息。看下面的启动代码来练习。
const getElementByID = document.getElementById("getAttr");
attrs = getElementByID.attributes;
n = attrs.length;
attrNameArray = [];
attrValueArray = [];
for (var i = 0; i < n; i++){
attrNameArray.push(attrs[i].nodeName);
attrValueArray.push(attrs[i].nodeValue);
}
console.log("Print attribute names and values with loop");
console.log(attrNameArray);
console.log(attrValueArray);
输出:
"Print attribute names and values with loop"
["id", "name", "message"]
["getAttr", "attr", "get attributes"]
在 JavaScript 中使用 jQuery 获取 HTML 元素的属性
以下代码使用 jQuery 使用 each() 函数获取属性的名称和值。each() 方法为每个匹配的元素运行一个函数/方法。
示例代码:
var element = $("#getAttr");
$(element[0].attributes).each(function() {
console.log(this.nodeName+':'+this.nodeValue);
});
输出:
"id:getAttr"
"name:attr"
"message:get attributes"
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe