Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickly select all elements with css background image

I want to grab all elements on a page that have a css background-image. I can do this via a filter function, but it's very slow on a page with many elements:

$('*').filter(function() {
    return ( $(this).css('background-image') !== '' );
}).addClass('bg_found');

Is there any faster way to select elements with background images?

like image 223
Jeremy Herrman Avatar asked Feb 10 '11 00:02

Jeremy Herrman


1 Answers

If there are any tags that you know will not have a background image, you can improve the selection be excluding those with the not-selector(docs).

$('*:not(span,p)')

Aside from that, you could try using a more native API approach in the filter.

$('*').filter(function() {
    if (this.currentStyle) 
              return this.currentStyle['backgroundImage'] !== 'none';
    else if (window.getComputedStyle)
              return document.defaultView.getComputedStyle(this,null)
                             .getPropertyValue('background-image') !== 'none';
}).addClass('bg_found');

Example: http://jsfiddle.net/q63eU/

The code in the filter is based on the getStyle code from: http://www.quirksmode.org/dom/getstyles.html


Posting a for statement version to avoid the function calls in .filter().

var tags = document.getElementsByTagName('*'),
    el;

for (var i = 0, len = tags.length; i < len; i++) {
    el = tags[i];
    if (el.currentStyle) {
        if( el.currentStyle['backgroundImage'] !== 'none' ) 
            el.className += ' bg_found';
    }
    else if (window.getComputedStyle) {
        if( document.defaultView.getComputedStyle(el, null).getPropertyValue('background-image') !== 'none' ) 
            el.className += ' bg_found';
    }
}
like image 117
user113716 Avatar answered Oct 16 '22 05:10

user113716