How to remove a style added with .css() function using jQuery?

Let's see how to remove style added in an HTML page using jQuery's .css() function?
Submitted by Pratishtha Saxena, on August 26, 2022

CSS can be added to an HTML page using different ways. One way of adding CSS is by defining it in the same tag where it has to be added. This is called inline CSS. Another way is by declaring the <style> tag in the head and defining all the CSS styling by classes, ids, and tag names. This is called internal CSS. The last way is by creating a new file with the .css extension and defining everything over there, and then link that file to the HTML page. This is termed external CSS.

But over here, let's work on either inline or internal CSS. Now, removing the styling of an element using jQuery can be done using some of its inbuilt jQuery methods.

Using .css() Function

This method is generally preferred when the styling properties are comparatively less. It helps to set or return the CSS properties. It can help to set properties of single or more selected elements.

Syntax:

$("selector").css({
    "prop1": "val1",
    "prop2": "val2",
    "prop3": "val3",
});

Each property can be specified individually. If only single property, say just the border, has to be removed then it will help us to specify the property and its value to it.

Example to remove a style added with .css() function using jQuery

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>Remove Style Added Using .CSS Function Using jQuery</h2>
    <div style="border: 5px solid goldenrod; background-color: brown; height: 100px; width: 200px;"></div>
    <br><br>
    <button type="button" id="button1">Remove CSS</button>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('#button1').click(function(){
            $('div').css('border','');
        })
    });
  </script>
</html>

Output:

Example: Remove a style added with .css() function

Here, as the border value has been set to none, it accepts it as 0px. Therefore, the border after clicking the button disappeared. This example just shows removing one property. Similarly, many properties can be set to none to remove the CSS styling completely.

Other methods to remove the styling is by using removeAttr() method, removeClass() method [remove only classes], etc.






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.