You can modify the event listener like this.
window.addEventListener('load', function() {
var h1Loop = document.querySelectorAll("h1");
for(var i = 0; i < h1Loop.length; i++) {
h1Loop[i].addEventListener("click", function () {
for(var j = 0; j < h1Loop.length; j++) {// all header elements are changed to black
h1Loop[i].style.color = "black"
}
this.style.color = "red";//clicked header element is changed to red
});
}
});
when a particular header element is clicked, first the colour of all header elements are changed to black. Then the colour of clicked element is changed to Red. In this way, the clicked element alone appears in red. Hope this helps.
I think below code will handle your request.
h1Loop[i].addEventListener("click", function (e) {
// Make all black
h1Loop.forEach(h1 => {
h1.style.color = "black";
});
// Make target h1 color red
e.target.style.color = "red";
});
you should use the event inside the click callback:
h1Loop[i].addEventListener("click", function (e) {
h1Loop.forEach(el => el.style.color="black");
this.style.color = "red";
});
Loop over the elements inside the event handler:
var h1Loop = document.querySelectorAll("h1");
for(var i = 0; i < h1Loop.length; i++) {
h1Loop[i].addEventListener("click", function () {
for(var j = 0; j < h1Loop.length; j++) {
h1Loop[j].style.color = (h1Loop[j] === this) ? "red" : "black";
}
});
}
I want to style the colour of the h1 elements to black that are not “this” on click. So it will turn the h1 red on click and not this to black.
<script>
window.addEventListener('load', function() {
var h1Loop = document.querySelectorAll("h1");
for(var i = 0; i < h1Loop.length; i++) {
h1Loop[i].addEventListener("click", function () {
this.style.color = "red";
not this.style.color = "black"
});
}
});
</script>
<h1>Test</h1>
<h1>Testing</h1>
<h1>Test One</h1>
Thank you, this worked for me. But why do we need to loop over again the H1’s in order to solve this problem? A bit confused….
Because when you click a element, the colour of previously clicked element must be turned to black. But we never know which previous element has been clicked. So the only possible solution is to make all header elements black so that the previously clicked element turns to black.