admin管理员组

文章数量:1401673

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

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

Share Improve this question asked Aug 8, 2009 at 10:25 Waleed EissaWaleed Eissa 10.6k16 gold badges63 silver badges82 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

use document.getElementsByTagName('*')

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

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; }');

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

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.

本文标签: javascriptWhat39s the equivalent of IE39s documentall in DOMStack Overflow