0

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

2

2 Answers 2

2

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>

0
0

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.