1

I have this :

var el1 = document.getElementById("el1");
var el2 = document.getElementById("el2");
var el3 = document.getElementById("el3");

el1.style.width = "100px";
el2.style.width = "100px";
el3.style.width = "100px";

Is there any ways to make this code shorter, and more maintainable ?

What if I need to have :

el1.style.width = "100px";
el2.style.width = "145px";
el3.style.width = "120px";

Thank you

kursus
  • 1,396
  • 3
  • 19
  • 35

2 Answers2

1

Well, you can do it by writing a loop:

var data = {
    el1: '100px',
    el2: '100px',
    el3: '100px'
};

for (var el in data) {
    document.getElementById(el).style.width = data[el];
}

Really, however, this kind of manipulation of multiple DOM elements is exactly the kind of task libraries like jQuery were written to do. "Have you tried jQuery?" is a bit of a joke on this site, but this is an occasion where it is very appropriate. In this case, for instance, using jQuery:

$('#el1, #el2, #el3').width(100);

Note that this also protects against cases where the elements don't exist. My code above, like yours, will cause an error if any of the elements aren't present in the DOM when the code is run.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
1

I guess you could write a function which does something like this, which lets you pass an Array of ids to get your Nodes and an Array of Objects with how to style each node, respectively.

function stylise(nodeIds, styles) {
    var i = nodeIds.length, j, e;
    while (i--) { // loop over elements
        if (!styles[i]) continue; // no style for this element, skip
        e = document.getElementById(nodeIds[i]); // get by id
        if (!e) continue; // no element, skip
        for (j in styles[i]) if (styles[i].hasOwnProperty(j)) { // loop styles
            e.style[j] = styles[i][j]; // apply style
        }
    }
}

stylise( // then in future to apply CSS just need
    ['el1', 'el2', 'el3'], // element ids
    [{width: '100px'}, {width: '145px'}, {width: '120px'}] // styles
);
Paul S.
  • 64,864
  • 9
  • 122
  • 138