0

Using only JavaScript, without the use of JQuery etc, How do I find the corresponding data attribute given an Id ?

Example

<div id="id-test" data-qa="data-qa-test">
</div>

Input: "id-test"

Output: "data-qa-test"

Is there a way in Javascript to take the code below, and find the corresponding data-qa automation tag locators?

Related question:

Javascript: Select all data-qa attributes on HTML Page

Background: Trying to replace Selenium ID locators, with our data qa attributes.

  • Given an id, use the id. Ids cannot repeat. If your markup is repeating ids, it is invalid by web standards and should be fixed. – Taplar Oct 09 '20 at 18:52

2 Answers2

1

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);

// get all "ids" and "data-qa"
var data = [];
elems.forEach(function(elem){
  data.push({
    "id": elem.id,
    "qa": elem.getAttribute('data-qa')
  });
});
console.log(data);

// get all "ids" and "data-qa" with "id" as key
var data = {};
elems.forEach(function(elem){
  data[elem.id] = {
    "id": elem.id,
    "qa": 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
  • are you able to write code to have an Array Pair class, Id with its corresponding Data-QA attribute? thanks –  Oct 11 '20 at 01:20
0

Is this what you mean, the question is a little confusing.

const ids = ["id-test","id-test1","id-test2","id-test3"];

const getData = (id) => document.querySelector(`#${id}`).dataset.qa;

const values = ids.map(id => getData(id));

console.log(values);
<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>
Bibberty
  • 4,670
  • 2
  • 8
  • 23
  • I'm actually looking for data-qa, so Input is Id, Output is data-qa –  Oct 09 '20 at 19:08
  • Then the code works, look at the console output. The function `getData(id)` is what you need from the snippet. – Bibberty Oct 09 '20 at 20:14