4. Add or Remove Specific CSS Classes (Using .addClass()
and .removeClass()
)
You can also directly add or remove CSS classes from elements.
Example: Add or Remove a CSS Class
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add/Remove CSS Class with jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="box"></div>
<button id="addClass">Add Highlight</button>
<button id="removeClass">Remove Highlight</button>
<script>
$(document).ready(function() {
$('#addClass').click(function() {
$('.box').addClass('highlight'); // Add 'highlight' class
});
$('#removeClass').click(function() {
$('.box').removeClass('highlight'); // Remove 'highlight' class
});
});
</script>
</body>
</html>
Add some CSS to the component!
#css
.box {
width: 100px;
height: 100px;
background-color: blue;
}
.highlight {
background-color: yellow;
}
Review:
.addClass('highlight')
: Adds the classhighlight
to the.box
element..removeClass('highlight')
: Removes the classhighlight
from the.box
element.- Click to see dynamic working on this query using JQuery!
Get the Current Value of a CSS Property
You can use the .css()
method to get the current value of a CSS property from an element.
Example: Get the Background Color of an Element
<script>
$(document).ready(function() {
// Get the background color of the box
var bgColor = $('.box').css('background-color');
console.log('The background color is:', bgColor);
});
</script>
Review:
.css('background-color')
: Retrieves the current background color of the.box
element and logs it to the console.
Results:
In jQuery, modifying CSS properties is straightforward with the .css()
method. You can:
- Modify single or multiple CSS properties.
- Add, remove, or toggle CSS classes.
- Get the current value of a CSS property.
This allows for flexible styling and dynamic updates to your webpage’s design.
Best Practices for Implementing Coding Filters!
To get the most out of coding filters, developers should follow best practices, such as creating reusable filter functions, keeping the logic modular, and ensuring consistent application of filters throughout the codebase. By doing so, developers can maintain clean, scalable code that is easier to modify and extend over time.