EN
JavaScript - find element by attribute
0
points
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>