Get, Set and Delete Div Background Image jQuery

Get, set and remove background from image using jquery; In this tutorial, you will learn how to get a div background image, how to set the div background image and how to div remove background image using jQuery.
Here you will learn step by step, get, set and remove background image using 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.CodeOne-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 = '//www.CodeOne.com/wp-content/uploads/2019/08/How-to-Encode-Decode-a-URL-Using-JavaScript.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('//www.CodeOne.com/wp-content/uploads/2019/08/How-to-Download-Install-XAMPP-on-Windows.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>
Conclusion
In this article, you have learned how to get, set and remove background image using the jQuery CSS property.