samedi 16 octobre 2021

Saving DOM elements in class attributes and manipulation

I have a webapp where i select a list of already existing elements in a webpage using a queryselector and then save them in a class attribute in order to modify them later on using some methods of my class.

the code looks like this:

class solutionToggler {
    constructor() {
        this.solutions = {}

        let show_solution_but = document.querySelectorAll(".solution_button")

        for (const [i,but] of show_solution_but.entries()) {
            const solution = selectSibling(but, ".solution")
            const id = "sol_"+i
            this.solutions[id] = [but,solution,{"state":true}]
            but.addEventListener('click', () => this.toggleSolution(id))
        }
    }

    toggleSolution(sol_id) {
        const [but,sol,s] = this.solutions[sol_id]
        s.state = !s.state
        but.textContent = s.state ? "👇" : "👆"
        sol.hidden = s.state
    }
}

the html element, like below, are placed around the page at the time i load the script.

<button class="solution_button">👇</button>
<div hidden class="solution">
    first
</div>

(full working code with html here: https://codepen.io/kenn7/pen/zYdrMOK)

My question is: Is this a good design pattern ? Is it a good thing to keep DOM elements in class attributes like this, or you I do something else, if so, how can i make it better?

Thx :)

Aucun commentaire:

Enregistrer un commentaire