We use css() Method in jQuery which gets or sets CSS properties for the selected element.
In order to use classes in jquery we have a set of class methods.
Gets or sets CSS properties for the selected element.
We can get specific property values using this method.
We can also set multiple css properties.
Its vary easy buit-in method used in js.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery css() Method Example</title>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<style>
.styledElement {
width: 200px;
height: 100px;
padding: 10px;
border: 1px solid #ccc;
margin: 20px;
}
</style>
</head>
<body>
<div id="exampleElement" class="styledElement">
<p>This is a styled element.</p>
</div>
<script>
// Using css() to set background color and font size
$("#exampleElement").css({
'background-color': 'lightblue',
'font-size': '18px'
});
// Using css() to get the font size and log it to the console
var fontSize = $("#exampleElement").css('font-size');
console.log("Font Size:", fontSize);
</script>
</body>
</html>
We have 4 class methods in order to access and modify a class in an element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Class Methods Example</title>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<div id="exampleElement">
<p>This is an example element.</p>
</div>
<script>
// Using addClass() to add the 'highlight' class
$("#exampleElement").addClass("highlight");
// Using hasClass() to check if the 'highlight' class is present
var hasHighlightClass = $("#exampleElement").hasClass("highlight");
console.log("Has 'highlight' class:", hasHighlightClass);
// Using removeClass() to remove the 'highlight' class
$("#exampleElement").removeClass("highlight");
// Using hasClass() again to check if the class is removed
hasHighlightClass = $("#exampleElement").hasClass("highlight");
console.log("Has 'highlight' class:", hasHighlightClass);
// Using toggleClass() to toggle the 'highlight' class
$("#exampleElement").toggleClass("highlight");
// Using hasClass() to check if the class is toggled
hasHighlightClass = $("#exampleElement").hasClass("highlight");
console.log("Has 'highlight' class:", hasHighlightClass);
</script>
</body>
</html>
The Concepts and codes you leart practice in Compilers till you are confident of doing on your own. A Various methods of examples, concepts, codes availble in our websites. Don't know where to start Down some code examples are given for this page topic use the code and compiler.