Home > Net >  Similar blocks of code found in 2 location in IF ELSE statement. Consider refactoring JS
Similar blocks of code found in 2 location in IF ELSE statement. Consider refactoring JS

Time:10-27

if (notesValue) {
  document.querySelector(`.card-${domain.id} .add-notes-button`).classList.add('notes-filled');
} else {
  document.querySelector(`.card-${domain.id} .add-notes-button`).classList.remove('notes-filled');
}

CodePudding user response:

The refactoring is simply done by using the second force param of the toggle Method:

Element.classList.toggle("className", forceBoolean)
MDN Docs DOMTokenList.toggle()

const EL_button = document.querySelector(`.card-${domain.id} .add-notes-button`);
EL_button.classList.toggle('notes-filled', notesValue);

CodePudding user response:

document
 .querySelector(`.card-${domain.id} .add-notes-button`)
 .classList
 .toggle('notes-filled', notesValue);

CodePudding user response:

Using toggle is a good idea but for a more general case where a method like that doesn't exist you could choose which method on the object to target e.g.:

document.querySelector(`.card-${domain.id} .add-notes-button`)
  .classList[notesValue ? 'add' : 'remove']('notes-filled');
  • Related