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
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.
3 Comments
Teemu
Just for a curiosity, what'll be the result of this code, if
runtimeStyle has been set for some element?Christian Jørgensen
That is probably a very good question :-) I have never heard of runtimeStyle before, so I am not able to answer that, sorry
Teemu
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.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
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
David Thomas
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)?zallarak
@DavidThomas how would one get a non-inline style then? Thanks for pointing this out.
msEmmaMays
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