Languages
[Edit]
EN

JavaScript - find element by attribute

0 points
Created by:
Dollie-Rutledge
476

In this article, we would like to show you how to find element by attribute in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

<div my-attribute="value">This is element with custom attribute.</div>
<script>

  // find element by custom attribute
  const handle = document.querySelector('[my-attribute="value"]');

  // use the element (e.g change background)
  handle.style.background = 'yellow';

</script>

 

Practical example

In this example, we get the handle to the element with custom attribute (my-attribute) using document.querySelector() and specifying the attribute's name and value inside square brackets.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div my-attribute="value">This is element with custom attribute.</div>
  <script>

    // find element by custom attribute
    const handle = document.querySelector('[my-attribute="value"]');

    // use the element (e.g change background)
    handle.style.background = 'yellow';

  </script>
</body>
</html>

References

  1. Document.querySelector() - Web APIs | MDN
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join