<style>
.heading {
color: red;
}
.button {
font-size: 18px;
}
.skyblue {
background-color: skyblue;
}
</style>
Whenever the "data-mh" attribute of an <h1> tag matches the id attribute of a <button> tag, clicking on that button will change its background color. The matching attribute will then be printed on a P tag. While this functionality works with the first button, it does not work with subsequent buttons.
/* how can do it by loop */
<h1 class="heading" data-mh="item1">Hello World</h1>
<button class="button" id="item1">Click Here</button>
<h1 class="heading" data-mh="item2">Hello World</h1>
<button class="button" id="item2">Click Here</button>
<h1 class="heading" data-mh="item3">Hello World</h1>
<button class="button" id="item3">Click Here</button>
<p id="demo"></p>
<!-- This Paragraph tag will print my attribute -->
<!-- HTML End -->
<script>
var x = document.querySelector(".heading").getAttribute("data-mh"); // This variable is to get Attribute of "data-mh"
var y = document.querySelector(".button"); // Button selection. By clicking this button I will get print my Attribute
var z = y.getAttribute("id"); // Getting button id to compaire with "data-mh" attribute
y.onclick = function() {
//If X (ID) and Z (Attribute) matching then working this Condition
if (x == z) {
y.classList.toggle("skyblue");
document.getElementById("demo").innerHTML = x+" "+z; // This line of code will print my Attribute on P tag
}
}
</script>