If your HTML structure looks something like this:
<div class="three" style="height: 445px;">
<p>Random content goes here.</p>
</div>
Then you can use the following JavaScript code to change the background image:
var elems = document.getElementsByClassName('three');
for (var i = 0, len = elems.length; i < len; i++){
if (parseInt(elems[i].style.height, 10) == 445) {
elems[i].style.backgroundImage = 'url(images/2.png)';
}
}
You can see a demonstration of this on JS Fiddle here, where we used background-color
instead of background-image
.
If your styling is done through CSS, then you need to utilize window.getComputedStyle()
like so:
var elems = document.getElementsByClassName('three');
for (var i = 0, len = elems.length; i < len; i++){
console.log(parseInt(window.getComputedStyle(elems[i], null).height, 10));
if (parseInt(window.getComputedStyle(elems[i], null).height, 10) == 445) {
elems[i].style.backgroundColor = 'red';
}
}
A similar demo using JS Fiddle can be found here.
For an easier approach with jQuery, you could simplify the code as follows:
$('.three').css('background-image', function(){
return $(this).height() == 445 ? 'images/2.png' : '';
});
Check out this JS Fiddle link for a demo with background-color
instead of background=image
.
Note that Internet Explorer handles things differently, and there's currentStyle()
available as an alternative. For more information on JavaScript, I recommend going through the Mozilla Developer Network's JavaScript documentation.
References: