How can i simplify this? (noob here)

Viewed 45

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 = "";
};

4 Answers

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 = '';

You can create an array of id and use forEach on that and add event listeners dynamically

['one', 'two', 'three', 'four'].forEach(x => {
   const element = document.getElementById(x);
   element.onclick = function(){
      element.innerHTML = '';
   }
})

Or you can put 1 class for all elements, and use document.getElementsByClassName().

    let eles = document.getElementsByClassName('yourClass');
    for (let i = 0; i < eles.length; i++) {
        eles[i].onclick = function () {
            eles[i].innerHTML = '';
        }
    }

May be this way ?

['one','two','three','four']
  .forEach(el=>document.getElementById(el)
                          .onclick=e=>e.target.textContent='');

proof:

['one','two','three','four']
  .forEach(el=>document.getElementById(el)
                          .onclick=e=>e.target.textContent='');
div {
  display: block;
  width: 3em;
  height:1.3em;
  border: 1px solid grey;
  margin: .7em 1em;
  padding: .3em;
  }
<div id="one"   contenteditable >div 1</div>
<div id="two"   contenteditable >div 2</div>
<div id="three" contenteditable >div 3</div>
<div id="four"  contenteditable >div 4</div>

or if All elements have the same class (named "clearOnClick" here on snippet)

document.querySelectorAll('.clearOnClick')
          .forEach(el=>el.onclick=e=>e.target.textContent='');

proof:

document.querySelectorAll('.clearOnClick')
          .forEach(el=>el.onclick=e=>e.target.textContent='');
.clearOnClick {
  display: block;
  width: 3em;
  height:1.3em;
  border: 1px solid grey;
  margin: .7em 1em;
  padding: .3em;
  }
<div id="one"   contenteditable class="clearOnClick">div 1</div>
<div id="two"   contenteditable class="clearOnClick">div 2</div>
<div id="three" contenteditable class="clearOnClick">div 3</div>
<div id="four"  contenteditable class="clearOnClick">div 4</div>

Related