mercredi 26 mai 2021

Simplifying lets and ifs in a JavaScript code

I have a lot of vars(let), each one of them connects to a tag that is going to be replaced and decide if the element is visible or not. if the tag replaced has any text at all it is going to be visible, if it dont have any, its going to change the element class to one that has a display:none;. I just cant believe there isnt any way to make this simplier, but i cant think of none, also if you have any tips in simplyfing ifs or vars feel free to give them. Thank you for the attention.

let visib1= "#product1#";
let visib2= "#product2#";
let visib3= "#product3#";
let visib4= "#product4#";
let visib5= "#product5#";
let visib6= "#product6#";
let visib7= "#product7#";
let visib8= "#product8#";
let visib9= "#product9#";

if(!visib1){
    document.getElementById('product1').classList.add("invisivel");
}

if(!visib2){
    document.getElementById('product2').classList.add("invisivel");
}

if(!visib3){
    document.getElementById('product3').classList.add("invisivel");
}

if(!visib4){
    document.getElementById('product4').classList.add("invisivel");
}

if(!visib5){
    document.getElementById('product5').classList.add("invisivel");
}

if(!visib6){
    document.getElementById('product6').classList.add("invisivel");
}

if(!visib7){
    document.getElementById('product7').classList.add("invisivel");
}

if(!visib8){
    document.getElementById('product8').classList.add("invisivel");
}

if(!visib9){
    document.getElementById('product9').classList.add("invisivel");
}

the html part:

<body>
<div class="text" id="product1">
      <p>new</p>
</div>
<div class="disccount" id="product2">
      <p>disccount</p>
</div>
<div class="text" id="product3">
      <p>new</p>
</div>
<div class="disccount" id="product4">
      <p>disccount</p>
</div>
<div class="text" id="product5">
      <p>new</p>
</div>
<div class="disccount" id="product6">
      <p>disccount</p>
</div>
<div class="text" id="product7">
      <p>new</p>
</div>
<div class="disccount" id="product8">
      <p>disccount</p>
</div>
<div class="text" id="product9">
      <p>new</p>
</div>
</body>

its an example html

Aucun commentaire:

Enregistrer un commentaire