DOM manipulation advice

I am taking up JS on my own. This endeavor exposes me to various ways of achieving the same thing in JS, which at times can be bewildering . Particularly, I am wondering about the correctness of the following ways of working with the DOM. Thank you in advance for your inputs!

I have a simple html page

<body>
        <h1 class="red">I am red</h1>
        <h2 class="blue">I am blue</h2>
        <h3 class="yellow">I am yellow</h3>
        <script src="app.js"></script>
</body>

Here, I am trying to change the color of the html elements with a click event

document.body.addEventListener("click", function (event) {
    if (!(event.target === document.body)) {
        event.target.style.color = event.target.classList;
    }
});



Array.from(document.body.children).forEach((child) => {
    child.addEventListener("click", function () {
        this.style.color = this.classList;
    });
});

What you are doing with the first listener on the body is a concept called event delegation. I think most devs would choose this method because it keeps the number of listeners to a minimum. I’m not sure if this is the type of feedback you are looking for?

@bbsmooth That was precisely the sort of feedback I was looking for. As I learn JS on my own , I always have the fear that I am wasting time learning something that has been deprecated or not used widely. I will definitely look into event delegation. Thanks for the pointer!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.