skip to Main Content

Consider the set of codes I have for my three elements of ids fill2a, show2, choice2:

         document.getElementById("fill2a").style.display="block"; 
         document.getElementById("show2").style.display="block";
         document.getElementById("choice2").style.display="block"; 

Can I replace the above code snippet into something like this? (I actually don’t know the format)

style.display=block for ids='fill2a','show2','choice2';

Can I create an array and then work? Explain kindly what to do.

3

Answers


  1. You can try creating an array of element’s id. Then iterate over them to set the style like the following way:

    const elementIdArr = ["fill2a", "show2", "choice2"];
    elementIdArr.forEach(id => document.getElementById(id).style.display = "block");
    
    Login or Signup to reply.
  2. You could use a for… in loop to loop over an array of ID’s:

    var ids = ["something", "something2", "something3"];
    for (let id of ids) document.getElementById(id).style.display = "block";
    <a id="something">Text</a>
    <a id="something2">Text</a>
    <a id="something3">Text</a>
    Login or Signup to reply.
  3. Don’t address the style of the elements directly.

    Write a stylesheet using classes and descendant combinators:

    .ancestor.active .fill,
    .ancestor.active .show,
    .ancestor.active .choice { display: block; }
    

    Then add the class on the ancestor:

    document.getElementById(‘#ancestor2’).classList.add(‘active’);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search