Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading