Sam Cross Sam Cross - 24 days ago 5
HTML Question

How to query a data attribute value in javascript (no jquery)?

If I have a grid made up of

ul's
(the rows) and
li's
(the cells), I wanted to get a specific cell based on the data attribute values of the
ul
and the
li
:

document.querySelectorAll(div.grid ul[data-${this.y}] li[data-${this.x}]'_


When I searched on MDN, I only found how to retrieve the
html element
based on the
data attribute
, but not it's value.

Any pointers would be greatly appreciated - also no
jQuery
please.

Answer

You could use the String interpolation and get it worked.

Here is what you could do.

document.addEventListener('DOMContentLoaded', function() {

  let ulData = 2,
    liData = 4;

  document.querySelector(`div.grid ul[data="${ulData}"] li[data="${liData}"]`).classList.add("red");
});
.red {
  color: red;
}
<div class="grid">
  <ul data="2">
    <li data="1">
      One
    </li>
    <li data="2">
      Two
    </li>
    <li data="3">
      Three
    </li>
    <li data="4">
      Four
    </li>
    <li data="5">
      Five
    </li>
  </ul>
</div>