Ned Batchelder
Ned Batchelder

Reputation: 376052

How to find all elements with a particular CSS style, without a JS library?

I'd like to write a bookmarklet to correct text styling on other people's pages. In particular, I'd like to find any element with "text-align: justify" and change them to "text-align: left". I'm not sure how to find those elements though. Because this is a bookmarklet to be used on arbitrary web pages, I'd rather not rely on any Javascript library (jQuery, etc) to help.

Upvotes: 2

Views: 227

Answers (2)

Šime Vidas
Šime Vidas

Reputation: 186103

Here:

var walkTheDOM = function walk ( node, func ) {
    if ( node.nodeType !== 1 ) return;
    func( node );
    node = node.firstChild;
    while ( node ) {
        walk( node, func );
        node = node.nextSibling;
    }
};

walkTheDOM( document.body, function ( elem ) {
    if ( getComputedStyle( elem ).textAlign === 'justify' ) {
        elem.style.textAlign = 'left';
    }
});

Live demo: http://jsfiddle.net/W3BUe/1/

Upvotes: 1

Nathan Wall
Nathan Wall

Reputation: 6788

This finds all elements with text-align: justify and sets the border to red. It should be plenty to get you started. Note: This is not very efficient, but there's not a good efficient solution to your request. To improve performance, try searching only relevant tags. (Maybe you only need to check Ps and DIVs?)

// Get all elements
var els = document.getElementsByTagName('*');
// Search for style: text-align = justify.
for(var i = 0, el; el = els[i]; i++) {
    if(getComputedStyle(el).textAlign == 'justify') {
        el.style.border = '1px solid #f00';
    }
}

Upvotes: 1

Related Questions