How can i simplify this? (noob here)

Appulino :

i got this very long block and i think that it can be simplify but i dont know how to do it

const one = document.getElementById("one");
const two = document.getElementById("two");
const three = document.getElementById("three");
const four = document.getElementById("four");

one.onclick = () => {
  one.innerHTML = "";
};
two.onclick = () => {
  two.innerHTML = "";
};
three.onclick = () => {
  three.innerHTML = "";
};
four.onclick = () => {
four.innerHTML = "";
};

ninja :

I agree with Alex, using a class on the elements you wish to run the logic on makes more sense. For example:

const elements = document.querySelectorAll('.js-clear-on-click');

elements.forEach(el => el.addEventListener('click', event => {
  el.textContent = '';
}));

Now you can reuse this functionality by just adding the class 'js-clear-on-click' on the DOM-element, so there will be no need to go back to your js-code and update it with 'five' for example.

Edit: If you wish to clear the element of all inner HTML, replace .textContent = ''; with .innerHTML = '';

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=345943&siteId=1