How can I set a variable in JavaScript using attributes other than tag, class or ID name?

So my question is quite simple, see the code below.
I would like to save the two spans in two different variables based on their value in the "data-language" attribute. Any idea how could I do this?

<div class="language-select">
          <span class="language-item" data-language="hu">HU </span>
          <span>/ </span>
          <span class="language-item" data-language="en"> EN</span>
        </div>

>Solution :

You can just use an attribute selector

const span1 = document.querySelector('[data-language="hu"]');
const span2 = document.querySelector('[data-language="en"]');

console.log(span1, span2);
<div class="language-select">
  <span class="language-item" data-language="hu">HU </span>
  <span>/ </span>
  <span class="language-item" data-language="en"> EN</span>
</div>

Leave a Reply