jQuery set, get and delete background image; Through this tutorial, i am going to show you how to set, get and delete/remove div background image using jQuery.
Get, Set and Delete Div Background Image jQuery
To set, get and delete background image in a Div using jQuery:
- jQuery Get Background Image
- jQuery Set Background Image
- jQuery Remove Background Image
- Example – jQuery Set, Get and Remove Background Image of Div
jQuery Get Background Image
Get the background image in jQuery; as shown below:
$(".btn-get").click(function() { var bg = $('div').css('background-image'); // get background image using css property bg = bg.replace('url(','').replace(')',''); alert(bg); });
jQuery Set Background Image
Use the following code to set background image of div in jQuery using CSS property; as shown below:
$(".btn-set").click(function() { var img = '//laratutorials.com/wp-content/uploads/2019/04/jQuery-Form-Validation-Custom-Error-Message.jpg'; var bg = $('div').css('background-image',"url(" + img + ")"); });
jQuery Remove Background Image
Use the following code remove/delete the background image of div using the jQuery CSS property; as shown below:
$(".btn-remove").click(function() { var bg = $('div').css('background-image','none'); });
Example – jQuery Set, Get and Remove Background Image of Div
See the following example for get the div background image, set the background image and delete/remove the background image using the jQuery css property; as shown below:
<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 = '//laratutorials.com/wp-content/uploads/2019/04/jQuery-Form-Validation-Custom-Error-Message.jpg'; 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('http://www.Laratutorials.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
To set, get and delete background image in a Div using jQuery; In this article, you have learned how to get, set and remove background image using the jQuery CSS property.