EN
JavaScript - style HTML elements with custom attribute only
0 points
In this article, we would like to show you how to style HTML elements containing custom attribute only using JavaScript.
Quick solution:
xxxxxxxxxx
1
var myElements = document.querySelectorAll('.class-name');
2
3
myElements.forEach((element) => {
4
if(element.hasAttribute('data-attribute-name')){
5
// do something with elements
6
}
7
});
In this example, we use hasAttribute()
method to check if the elements with class1
also contain myAttribute
, then we style only the ones that do have the attribute.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div class="class1" data-attribute-name="value">element1</div>
5
<div class="class1">element2</div>
6
<div class="class1" data-attribute-name="value">element3</div>
7
<script>
8
// get elements by class
9
var myElements = document.querySelectorAll('.class1');
10
11
myElements.forEach((element) => {
12
if(element.hasAttribute('data-attribute-name')){
13
// do something with elements (e.g style them):
14
element.style.backgroundColor = 'yellow';
15
}
16
});
17
</script>
18
</body>
19
</html>
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div class="class1" data-attribute-name="value1">element1</div>
5
<div class="class1" data-attribute-name="value2">element2</div>
6
<div class="class1">element3</div>
7
<script>
8
// get elements by class
9
var myElements = document.querySelectorAll('.class1');
10
11
myElements.forEach((element) => {
12
if(element.getAttribute('data-attribute-name') == 'value1'){
13
// do something with elements (e.g style them):
14
element.style.backgroundColor = 'yellow';
15
}
16
});
17
</script>
18
</body>
19
</html>