Reputation: 5525
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.
Upvotes: 1
Views: 204
Reputation: 97727
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]);
}
}
Upvotes: 2
Reputation: 337
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.
Upvotes: 3
Reputation: 1063
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
Upvotes: -1