Javascript:在HTML页面上选择所有data-qa属性 [英] Javascript: Select all data-qa attributes on HTML Page
问题描述
仅使用JavaScript,而不使用JQuery等,选择具有特定数据属性(例如data-qa)的所有属性名称的最有效方法是什么。
Using only JavaScript, without the use of JQuery etc, what is the most efficient way to select all attributes names that have a certain data attribute (let's say data-qa).
<p data-foo="0"></p><br/><h6 data-qa="apple"></h6>
<p data-foo="0"></p><br/><h6 data-qa="book"></h6>
<p data-foo="0"></p><br/><h6 data-qa="car"></h6>
预期结果应为列表:
apple
book
car
此问题获取父元素,我需要属性本身。 选择所有带有 data-元素属性而不使用jQuery
This question gets the parent elements, I want the attributes themselves. Select all elements with "data-" attribute without using jQuery
资源:
推荐答案
下面的代码通过使用 document.querySelectorAll
,然后遍历它们并使用 Element.getAttribute
访问属性的值。
The code below works by getting all of the elements using document.querySelectorAll
, and then looping through them and accessing the value of the attribute using Element.getAttribute
.
function getAllDataAttrs(name) {
// name is the name of the data attribute (excluding "data-")
// returns an array of the nonzero, nonempty values as strings
let elements = document.querySelectorAll(`[data-${name}]`);
let result = [];
for (let i = 0; i < elements.length; i++) {
let attr = elements[i].getAttribute(`data-${name}`);
if (attr !== null && attr !== '0' && attr !== '') {
result.push(attr);
}
}
return result;
}
console.log(getAllDataAttrs('foo'));
<p data-foo="0"></p><br/><h6 data-foo="apple"></h6>
<p data-foo="0"></p><br/><h6 data-foo="book"></h6>
<p data-foo="0"></p><br/><h6 data-foo="car"></h6>
这篇关于Javascript:在HTML页面上选择所有data-qa属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!