1

Is there a way to get all elements on the DOM with the presence of a certain CSS property? Say I wanted to get all elements with a background-image CSS value -- how could I select all of them? I preferably want to avoid using Jquery.

3 Answers 3

3

To be absolutely sure, you have get the style like this:

var elms = document.all ? document.all : document.body.getElementsByTagName("*");
for (i = 0; i < elms.length; i++) {
    if ((elms[i].currentStyle && elms[i].currentStyle.backgroundImage.length > 0) ||
    (window.getComputedStyle &&
    window.getComputedStyle(elms[i]).getPropertyValue("background-image"))) {
        alert('found one!');
    } 
}​

CurrentStyle is for IE, getComputedStyle is for the rest.

Sign up to request clarification or add additional context in comments.

3 Comments

Just for a curiosity, what'll be the result of this code, if runtimeStyle has been set for some element?
That is probably a very good question :-) I have never heard of runtimeStyle before, so I am not able to answer that, sorry
I'm not sure if it's IE-only, but in IE you can set runtimeStyle to make a kind of an inline style for an element. However this style can't be seen when retrieving innerHTML or outerHTML, though it is rendered to the page.
2

on a modern browser you can use getComputedStyles

var elements = document.getElementsByTagName("*");
var haveBg = new Array();
for (i = 0; i < elements.length; i++) {
    var style = window.getComputedStyle(elements[i], null);
    if (style.getPropertyValue("background-image") != 'none') {
        haveBg.push(elements[i]);
    } 
}

Comments

-1
var elms = document.all ? document.all : document.getElementsByTagName("*");
for (i = 0; i < elms.length; i++) {
   if (elms[i].style.backgroundImage.length > 0) {
        alert('found one!');
    } 
}

It would be better to use the exact tag name rather then '*' if you know what it would be before hand

3 Comments

I'm not a hundred percent sure any more, but doesn't the style property only look at in-line styles (from the style attribute)?
@DavidThomas how would one get a non-inline style then? Thanks for pointing this out.
True - I guess if you want to look inside the CSS you'd have to do it by hand using document.styleSheets - it would probably be pretty difficult dev.opera.com/articles/view/dynamic-style-css-javascript

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.