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

shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34
  • Once you have the elements, you can loop over them and use https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute – Rafi Sep 30 '20 at 08:16
  • Also, please don't add irrelevant tags like [ecma]. [ecma] refers to the organization, and it harms the ability for other users to find this question. – shreyasm-dev Oct 04 '20 at 01:18

2 Answers2

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>
ElectricShadow
  • 683
  • 4
  • 16
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>
farinspace
  • 8,422
  • 6
  • 33
  • 46