SimpleTuts.com

jQuery Methods for CSS Manipulation and Dimension Control

addClass() Method

Adds a CSS class to selected elements.

$("#element").addClass("highlight");

removeClass() Method

Removes a CSS class from selected elements.

$("#element").removeClass("highlight");

toggleClass() Method

Toggles a CSS class on selected elements.

$("#element").toggleClass("highlight");

css() Method

Sets or retrieves CSS properties and values.

$("#element").css({
        "background-color": "blue",
        "color": "white",
        "font-size": "20px"
    });

height() Method

Gets or sets the height of selected elements.

var height = $("#element").height();
    alert("Height of the element: " + height + "px");

width() Method

Gets or sets the width of selected elements.

var width = $("#element").width();
    alert("Width of the element: " + width + "px");

All in one Example:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Styling HTML using jQuery</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script>
        $(document).ready(function(){
            $(".btn1").click(function(){
                $(".mypara").addClass("newstyle");
            });
            $(".btn2").click(function(){
                $(".mypara").removeClass("newstyle");
            });
            $(".btn3").click(function(){
                $(".mypara").toggleClass("newstyle");
            });
            $(".btn4").click(function(){
                $(".mypara").css("color","red");
            });
            $(".btn5").click(function(){
                $(".mypara").css({
                    "color":"red",
                    "background-color":"yellow",
                    "padding":"15px"
                });
            });

            $(".btn6").click(function(){
                $(".mypic").width(400);
                $(".mypic").height(400);
            });
        });
    </script>
</head>
<body>
    
    <style>
        .newstyle{
            background-color: aquamarine;
            padding: 15px;
        }
    </style>

    
    <p class="mypara" >
        Lorem ipsum dolor sit amet consectetur, adipisicing elit. <br>
        Possimus molestiae pariatur quod, distinctio itaque modi molestias<br> 
        dignissimos recusandae explicabo accusamus inventore aliquid soluta<br>
        doloribus quo autem praesentium optio numquam harum.
    </p>
    <img src="flowers.jpg" class="mypic" alt="">
    <br><br>

    <button class="btn1">Add class</button>
    <button class="btn2">Remove class</button>
    <button class="btn3">Toggle class</button>
    <button class="btn4">Change single style</button>
    <button class="btn5">Change multiple styles</button>
    <button class="btn6">Change height and width</button>

</body>
</html>
Run Code