Search code examples
javascriptcssdomwalkthrough

javascript: insert large CSS string in one go, into every DOM element


This is a two part question - first I need to get every element that is a child (or subchild, etc) of a parent element, and then I need to reset it's style. As such, I'm looking to do something like the following:

var everything = parent.getEveryElementBelowThisOne();
for (i=0; i<everything.length; i++)
    everything[i].css = "font: 100%/100% Verdana,Arial,Helvetica,sans-serif; color: rgb(0, 0, o); margin: 0px; padding: 0px; border-collapse: collapse; border-width: 0px; border-spacing: 0px; text-align: left; outline: 0pt none; text-transform: none; vertical-align: middle; background-color: transparent; table-layout: auto; min-width: 0px; min-height: 0px;"

So my questions are as follows:

  • Is there a javascript function that will effectively walk through the DOM below a given element?
  • Is there a javascript function that will let me set a CSS string like that? Or do I have to have a whole bunch of entries like:
everything[i].style.font = ...;
everything[i].style.color = ...;
[...]
everything[i].style.min-height: ...;

jQuery is not an option.


Solution

  • Instead of a string, I would use an object, much more readable and maintainable:

    var new_css = {
        font: '100%/100% Verdana,Arial,Helvetica,sans-serif',
        color: 'rgb(0, 0, o)',
        margin: '0px',
        padding: '0px',
        borderCollapse: 'collapse'
        /* rest here ... */
    }
    

    Then use a helper function, something like:

    function setStyle (element, style) {
        for (var n in style) {
            element[n] = style[n];
        }
    }
    

    and into your for loop:

    for (i=0; i<everything.length; i++) setStyle(everything[i],new_css);
    

    A note about the setStyle function (before people downvote me for this like last time), I purposely did not use a hasOwnProperty to check the elements of style because in this case, and in most cases we are using an object not inherited from anything. If you construct your new_css object any other way or if you use a library (prototype, I'm looking at you) that modify Object's prototype which may cause problems then feel free to add the hasOwnProperty check. Anyway, setting nonexistent style values are mostly harmless. And without a hasOwnProperty check you can use inheritence to compose style objects.