Reputation:
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>
Expected result should be list :
apple
book
car
This question gets the parent elements, I want the attributes themselves. Select all elements with "data-" attribute without using jQuery
Resources:
Selenium find element via Data-Qa attribute
Data-QA Attribute: A better way to select elements for UI test automation
Upvotes: 0
Views: 3990
Reputation: 690
The code below works by getting all of the elements using document.querySelectorAll
, mapping the elements to the values of the data attributes, and then filtering out the ones that are falsy or '0'
.
let getAllDataAttrs = name => Array.from(
document.querySelectorAll(`[data-${name}]`)
).map(elem => elem.getAttribute(`data-${name}`))
.filter(val => val && val !== '0');
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>
Upvotes: 3
Reputation: 8801
For reference, below is essentially the core vanilla javascript functionality needed ...
Using querySelectorAll
, querySelector
and getElementById
should get you started.
// get "data-qa" value by "id"
var data = document.getElementById('id-test2').getAttribute('data-qa');
console.log(data);
// get "id" value by "data-qa"
var data = document.querySelector('[data-qa="data-qa-test2"]').id;
console.log(data);
// get all elements with attribute "data-qa"
var elems = document.querySelectorAll('[data-qa]');
// get all "ids"
var data = [];
elems.forEach(function(elem){
data.push(elem.id);
});
console.log(data);
// get all "data-qa"
var data = [];
elems.forEach(function(elem){
data.push(elem.getAttribute('data-qa'));
});
console.log(data);
<div id="id-test" data-qa="data-qa-test"></div>
<div id="id-test1" data-qa="data-qa-test1"></div>
<div id="id-test2" data-qa="data-qa-test2"></div>
<div id="id-test3" data-qa="data-qa-test3"></div>
Upvotes: 0