Get, Set and Delete Div Background Image jQuery

Get Background image
You can use the below code for getting the background image in jQuery.
$(".btn-get").click(function() {
var bg = $('div').css('background-image'); // get background image using css property
bg = bg.replace('url(','').replace(')','');
alert(bg);
});
Set Background Image
You can use the below code for setting the background image using the jQuery CSS property.
$(".btn-set").click(function() {
var img = '//www.tutsmake.com/wp-content/uploads/2019/08/How-to-Encode-Decode-a-URL-Using-JavaScript.jpeg';
var bg = $('div').css('background-image',"url(" + img + ")");
});
Remove Background Image
You can use the below code for removing the background image using the jQuery CSS property.
$(".btn-remove").click(function() {
var bg = $('div').css('background-image','none');
});
Let’s take an Example
Here we will take an example, in this example we will get the div background image, we will set the background image and delete/remove the background image using the jQuery css property.
<html>
<head>
<title> How to get, set and remove background image attribute example</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(function() {
$(".btn-get").click(function() {
var bg = $('#bg-img').css('background-image');
bg = bg.replace('url(','').replace(')','');
alert(bg);
});
$(".btn-remove").click(function() {
var bg = $('#bg-img').css('background-image','none');
});
$(".btn-set").click(function() {
var img = '//name-withlocation.jpeg';
var bg = $('#bg-img').css('background-image',"url(" + img + ")");
});
});
</script>
<style>
.card{
margin: 30px;
}
</style>
</head>
<body>
<div class="card">
<div id="bg-img" style="background-image: url('//name-with-location.jpeg'); width: 1000px; height: 500px;">
</div>
</div>
<button type="type" class="btn-get">Get background image</button>
<button type="type" class="btn-set">Set background image</button>
<button type="type" class="btn-remove">Remove background image</button>
</body>
</html>
Check This Also
Difference between AngularJS and Angular 2 Make a Mobile app in just 10 minutes With Ionic Framework Angular 9: What to Expect in New Version of Angular Alert (Toaster) Notifications in Angular 8Tags: website development company in delhi|| website designing company in delhi || b2b portal development company || magento development company in delhi || website redesigning company in delhi