tags:

views:

200

answers:

4

I basically want to dynamically apply some style to all elements in a page, I know document.all is proprietary to IE, so, what's the equvalent (if any) in DOM? Is there an equivalent to * in css in DOM?

Note: Don't want to use JQuery or any other JS lib for this, just JS, thanks

+5  A: 

use document.getElementsByTagName('*')

The World Wide Web Consortium gives a clear specification of this method (Search for getElementsByTagName).

Scharrels
Thanks a lot ..
Waleed Eissa
A: 

Yep, I have just tested documentAll document.getElementsByTagName("*") on Safari, Explorer6, Opera and Firefox and seems to work for all them :)

And
Hmm, this is very interesting, I always knew document.all is proprietary to MS IE, so I didn't even try to see if it works in other browsers. I still prefer to do it the 'standards' way, but I think it's very interesting that other browser vendors implemented it, thanks for noting this
Waleed Eissa
Sorry Waleed, that that was a typo, i meant document.getElementsByTagName("*") works on all browser.
And
+3  A: 

As Scharrels said, you can use document.getElementsByTagName('*'). But you should note that applying styles to every single element on a page is going to impact performance. It would be better to dynamically create a <style> tag and add the styles in there:

function addStyles(styles) {
    var styleTag = document.createElement('style');
    styleTag.type = 'text/css';
    try {
        styleTag.appendChild(document.createTextNode(styles));
    } catch(e) {
        /* Exception thrown in IE */
        styleTag.stylesheet.cssText = styles;
    }
    document.getElementsByTagName('head')[0].appendChild(styleTag);
    return styleTag;
}

Usage:

addStyles('* { color: red; }');
J-P
Oh, actually I'm only using this for a bookmarklet. I'm creating a bookmarklet for google Chrome to change the background and text colors, so it's not a problem if it affects performance, but thanks for noting this anyway.
Waleed Eissa
A: 

Applying a style to all elements is not something that you would normally do, so what is it that you are going to use it for?

There are some styles that you can't apply to all elements. A select element for example doesn't support setting borders in all browsers. Setting margin on inline elements can have varying unexpected results...

Some styles are inherited, so if you for example apply a font-size to the body element, that would be inherited by any elements that doesn't already have a specific font-size set.

You can use the cascading in CSS to change the style on a lot of elements. If you for example have this style defined:

.highlight div.info { background: #ffc; }
.highlight strong { color: #f00; }

Setting className="highlight" to the body tag would give every div inside with class="info" a light yellow background and every strong element red text.

Guffa