0

I want to simplify the following code:
(As you can see I have a lot of document.getElementById)

clickText() {
  document.getElementById("choiceInput").style.display = "none";
  document.getElementById("dateInput").style.display = "none";
  document.getElementById("textInput").style.display = "block";
  document.getElementById('buttonFont').classList.remove('buttonUnselectAfterClick');
  document.getElementById('buttonFont').classList.add('buttonSelectAfterClick');
  document.getElementById('buttonCalendar').classList.remove('buttonSelectAfterClick');
  document.getElementById('buttonCalendar').classList.add('buttonUnselectAfterClick');
  document.getElementById('buttonBoolean').classList.remove('buttonSelectAfterClick');
  document.getElementById('buttonBoolean').classList.add('buttonUnselectAfterClick');
}

Also, I'm using reactjs.

9
  • 1
    Use class instead Commented Sep 25, 2018 at 7:12
  • @BhojendraRauniyar I can't, I need to have distinct elements Commented Sep 25, 2018 at 7:13
  • Maybe use jQuery? Commented Sep 25, 2018 at 7:19
  • Create a helper function and call it like addClassToElement('buttonFont', 'buttonUnselectAfterClick'). Commented Sep 25, 2018 at 7:20
  • 2
    @Alessio you need to learn a bit more about react as what you are asking can be solved an elegant "react" way Commented Sep 25, 2018 at 7:27

1 Answer 1

2

You can use Map, Set and for...of loop to simplify the code a little bit by grouping them, and no library and framework is needed:

const displayList = new Map([['choiceInput', 'none'], ['dateInput', 'none'], ['textInput', 'block']]);
const eventList = new Set(['buttonFont', 'buttonCalendar', 'buttonBoolean']);

clickText() {
  // For display attr
  for([key, val] of displayList) {
     document.getElementById(key).style.display = val;
  }

  // For events
  for(item of eventList) {
   document.getElementById(item).classList.remove('buttonUnselectAfterClick');
document.getElementById(item).classList.add('buttonUnselectAfterClick');
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

You should wrap into methods for a cleaner solution. But it's a good option
@segu Thanks! I have wrapped it into the same function.
Good solution, but you should extract creating Map and Set out form the click. You don't need to create this list every time button clicked

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.