简体   繁体   中英

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

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

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);
document .querySelector(`.card-${domain.id} .add-notes-button`) .classList .toggle('notes-filled', notesValue);

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 eg:

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

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