skip to Main Content

I have 12 div that must have the same attributes and i don’t find the way to simplify my code.
In this example below the variables ‘blue’ and ‘red’ have both the same 3 settings and i would like to know if there is a way to declare the setAttributes once instead of 12 times.

let blue = document.getElementById('blue');
blue.setAttribute('style', 'text-decoration : underline');
blue.setAttribute('style', 'color : #00ff00');
blue.setAttribute("href", "#zag");

let red = document.getElementById('red');
red.setAttribute('style', 'text-decoration : underline');
red.setAttribute('style', 'color : #00ff00');
red.setAttribute("href", "#zag");

2

Answers


  1. This can be done using a for loop:

    const elementIds = ["blue", "red"]
    
    for (let elementId of elementIds) {
        const element = document.getElementById(elementId);
        element.setAttribute('style', 'text-decoration : underline');
        element.setAttribute('style', 'color : #00ff00');
        element.setAttribute("href", "#zag");
    }
    
    Login or Signup to reply.
  2. Use a loop … Create an array with all ids you want to update. The iterate over the collection and get the element for each id.

    let ids = ['blue', 'red', ...];
    for (let id of ids) {
      let elem = document.getElementById(id);
      if (!elem) continue;
    
      elem.setAttribute(...);
      ...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search