3
In my project, I have very similar functions, with the same intention, however, as it is a DOM class exchange function (classList.replace
), I ended up making a very repetitive code, and I’d like to reduce it to make it reusable in the future. However, despite several attempts with loops like for...if
and forEach
, I ended up crashing, and for lack of programming logic experience, because I study programming only 6 months, I could not.
Here’s the code:
handleLeftAnswer() {
$leftDiv.classList.replace('leftside-div', 'leftside-div-js');
$centerDiv.classList.replace('centerside-div', 'centerside-div-js-no-display');
$rightDiv.classList.replace('rightside-div', 'rightside-div-js-no-display');
}
handleMidAnswer() {
$centerDiv.classList.replace('centerside-div', 'centerside-div-js');
$rightDiv.classList.replace('rightside-div', 'rightside-div-js-no-display');
$leftDiv.classList.replace('leftside-div', 'leftside-div-js-no-display');
}
handleRightAnswer() {
$rightDiv.classList.replace('rightside-div', 'rightside-div-js');
$centerDiv.classList.replace('centerside-div', 'centerside-div-js-no-display');
$leftDiv.classList.replace('leftside-div', 'leftside-div-js-no-display');
}
What I tried to:
handleRightAnswer(rightOne) {
const options = ['left', 'center', 'right'];
console.log(rightOne);
switch (rightOne) {
case rightOne: 'left'; break;
case rightOne: 'center'; break;
case rightOne: 'right'; break;
}
for (const option of options) {
const isThisTheRightAnswer = option === rightOne;
const element = document.querySelector(`.${option}side-div`);
console.log(element);
isThisTheRightAnswer ? element.classList.replace(`${option}side-div`, `${option}side-div-js`)
: element.classList.replace(`${option}side-div`, `${option}side-div-js-no-display`)
}
}
What mistakes did they make in that attempt:
rightOne
was coming back as amouseEvent
- The three elements were acting together and exchanging their classes at once, rather than separately.
isThisTheRightAnswer
was returning asfalse
, and I couldn’t figure out how to make it to returntrue
.
Again, forgive me for my ignorance and lack of practice, I would really like to know how I can work more my logical reasoning to improve my code in the future, and I, a beginner in programming, count on your help to help me in this.
Puts, something so simple and I was trying to solve it in the most complex ways there are. Thanks bro!
– PiviaN