I have a div tag which can contain either 1 of the 3 images I have. Imagea, Imageb and ImageC as the background.
What I would like to do is write a if statement to check if background image the div contains.
var myDiv = document.getElementById("divtag1");
if(myDiv.style.backgroundImage == "url('images/plane.png')" ) {
// Doing something
}
This doesn't seem to work, any help is welcomed.
If you want to use JQuery
var background = $('.element').css('background-image') if (background.indexOf("placehold.it/350x150") >= 0) { $('.element').css('border', '5px solid black'); }
.element { background-image: url('http://placehold.it/350x150'); width: 350px; height: 150px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="element"></div>
I have not tested this code so you may need to fiddle with it a bit but to check the background image you would do something like:
if (myDiv.style.backgroundImage == "url('images/plane.png')")
{
//DO SOMETHING.
}
You want the .style
property. I don't think you'll need .getComputedStyle()
but I'll link to that too.
So something like:
var myDiv = document.getElementById("divtag1");
if(myDiv.style.backgroundImage === "url('images/plane.png')" ) {
// Doing something
}
Here ye go. If you don't want to use regex, instead of if(imgtest.test(backgroundimage))
you can also use if(backgroundimage.indexOf('lion') > -1)
var lion = document.getElementById('lion'); var backgroundimage = window.getComputedStyle(lion).backgroundImage; console.log(backgroundimage) var imgtest = /lion/i; //regex to test for whatever string you need if (imgtest.test(backgroundimage)) { console.log("Yes, this is a lion.") }
#lion { background: url(http://www.slate.com/content/dam/slate/articles/health_and_science/science/2015/07/150730_SCI_Cecil_lion.jpg.CROP.promo-xlarge2.jpg); background-size: contain; width: 500px; height: 357px; }
<div id="lion"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.