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?
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';
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With