简体   繁体   中英

Vanilla JS not this on click event

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>

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.

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";
        });

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";

        });

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";
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM