jQuery addClass() Method

jQuery | addClass() Method: Learn about the jQuery addClass() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 16, 2022

addClass() Method

Generally, a CSS class is declared when the HTML of the page is written down. At that time only the classes are specified for the elements. But, what if some of the classes are to be added afterward? There are many situations when we need to add a particular class after the implementation of an event on the element. This cannot be declared using HTML. This can be achieved by using jQuery's method – addClass().

The addClass() method in jQuery helps to add some classes to the element without disturbing the already declared classes. Therefore, this method does not affect the predefined classes, it just adds the new class to the element. Using this method, we cannot remove the attributes of the classes.

addClass() Method Syntax

$('selector').addClass('className');

This method takes in only a single parameter i.e., the class name. The class, here, is a CSS class. This class has to be already defined in the style part of the document. The below example shows the implementation of this method. A class gets added to the image tag when the button is clicked.

jQuery addClass() Method Example

<!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>
    <style>
      .size{
      height: 200px;
      width: 300px;
      }
    </style>
  </head>
  
  <body>
    <h2>jQuery - AddClass</h2>
    <p>Click the button to add some class to the selected element.</p>
    <button>AddClass</button>
    <hr>
    <img id="myImg" src="https://media.istockphoto.com/photos/mountain-landscape-picture-id517188688?k=20&m=517188688&s=612x612&w=0&h=i38qBm2P-6V4vZVEaMy_TaTEaoCMkYhvLCysE7yJQ5Q=">
    <hr>
    <h3 style="color:crimson ;"></h3>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('button').click(function(){
            $('img').addClass('size');
            $('h3').html('Class Has Been Added !');
        })
    });
  </script>
</html>

Output:

Example 1: jQuery addClass() Method


All jQuery Examples

Comments and Discussions!

Load comments ↻





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