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:
xxxxxxxxxx
1
<div my-attribute="value">This is element with custom attribute.</div>
2
<script>
3
4
// find element by custom attribute
5
const handle = document.querySelector('[my-attribute="value"]');
6
7
// use the element (e.g change background)
8
handle.style.background = 'yellow';
9
10
</script>
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.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div my-attribute="value">This is element with custom attribute.</div>
5
<script>
6
7
// find element by custom attribute
8
const handle = document.querySelector('[my-attribute="value"]');
9
10
// use the element (e.g change background)
11
handle.style.background = 'yellow';
12
13
</script>
14
</body>
15
</html>