This jQuery Cheatsheet is For You!

  1. Include jQuery : Adding jQuery to HTML
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>

  2. jQuery : jQuery is a lightweight, "write less, do more", JavaScript library.

    The purpose of jQuery is to make it much easier to use JavaScript on your website.

    jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.

    jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

    The jQuery library contains the following features:
    • HTML/DOM manipulation
    • CSS manipulation
    • HTML event methods
    • Effects and animations
    • AJAX
    • Utilities

    Tip : In addition, jQuery has plugins for almost any task out there.

    Example
    <head>
    <script>
    $(document).ready(function(){
    $("button").click(function(){
        $("p").hide();
        });
    });
    </script>
    </head>
    
    <body>
    <h2>Welcome to JQuery World</h2>
    <p>This is Kaushal Jacker</p>
    <p>From SpecBits.</p>
    
    <button>Hide Details</button>
    </body>
    Note :- The purpose of jQuery is to make it much easier to use JavaScript on your website.

  3. jQuery Syntax : The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s).

    Basic syntax is: $(selector).action()
    A $ sign to define/access jQuery
    A (selector) to "query (or find)" HTML elements
    A jQuery action() to be performed on the element(s)

    Examples:
    $(this).hide() - hides the current element.
    $("p").hide() - hides all (p) elements.
    $(".test").hide() - hides all elements with class="test".
    $("#test").hide() - hides the element with id="test".

  4. jQuery Selectors : The jQuejQuery selectors are one of the most important parts of the jQuery library.

    jQuery selectors allow you to select and manipulate HTML element(s).

    jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.

    All selectors in jQuery start with the dollar sign and parentheses: $().

    The element Selector : The jQuery element selector selects elements based on the element name.

    You can select all (p) elements on a page like this:
    $("p")
    Example
    <script>
    $(document).ready(function(){
    $("button").click(function(){
    $("p").hide();
    });
    });
    </script>
    
    <h2>Welcome to JQuery World</h2>
    <p>This is Kaushal Jacker</p>
    <p>From SpecBits.</p>
    
    <button>Hide Details</button>

    The #id Selector : The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.

    An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

    To find an element with a specific id, write a hash character, followed by the id of the HTML element:
    $("#test")

    Example
    <script>
    $(document).ready(function(){
    $("button").click(function(){
    $("#test").hide();
    });
    });
    </script>
    
    <h2>Welcome to JQuery World</h2>
    <p>This is Kaushal Jacker</p>
    <p id="test">From SpecBits.</p>
    
    <button>Hide Details</button>

    The .class Selector : The jQuery .class selector finds elements with a specific class.

    To find elements with a specific class, write a period character, followed by the name of the class:
    $(".test")

    Example
    <script>
    $(document).ready(function(){
    $("button").click(function(){
    $(".test").hide();
    });
    });
    </script>
    
    <h2 class="test">Welcome to JQuery World</h2>
    <p class="test">This is Kaushal Jacker</p>
    <p>From SpecBits.</p>
    
    <button>Hide Details</button>

  5. jQuery Event Methods : jQuery is tailor-made to respond to events in an HTML page.

    All the different visitors' actions that a web page can respond to are called events.

    An event represents the precise moment when something happens.

    Examples:
    • moving a mouse over an element
    • selecting a radio button
    • clicking on an element

    The term "fires/fired" is often used with events.

    jQuery Syntax For Event Methods : In jQuery, most DOM events have an equivalent jQuery method.

    To assign a click event to all paragraphs on a page, you can do this:
    $("p").click();

    Commonly Used jQuery Event Methods

    $(document).ready() This is to prevent any jQuery code from running before the document is finished loading (is ready).

    It is good practice to wait for the document to be fully loaded and ready before working with it.

    This also allows you to have your JavaScript code before the body of your document, in the head section.
    $(document).ready(function(){
    
    // jQuery methods go here...
    
    });
    Note :- Here are some examples of actions that can fail if methods are run before the document is fully loaded:
    • Trying to hide an element that is not created yet
    • Trying to get the size of an image that is not loaded yet

    Tip :- The jQuery team has also created an even shorter method for the document ready event:
    $(function(){
    
    // jQuery methods go here...
    
    });

    click() The click() method attaches an event handler function to an HTML element.

    The function is executed when the user clicks on the HTML element.
    <script>
    $(document).ready(function(){
    $("p").click(function(){
    $(this).hide();
    });
    });
    </script>
    
    <p>If you click on me, I will disappear.</p>
    <p>Click me away!</p>
    <p>Click me too!</p>

    dblclick() The dblclick() method attaches an event handler function to an HTML element.

    The function is executed when the user double-clicks on the HTML element:
    <script>
    $(document).ready(function(){
    $("p").dblclick(function(){
    $(this).hide();
    });
    });
    </script>
    
    <p>If you double-click on me, I will disappear.</p>
    <p>Click me away!</p>
    <p>Click me too!</p>

    mouseenter() The mouseenter() method attaches an event handler function to an HTML element.

    The function is executed when the mouse pointer enters the HTML element:
    <script>
    $(document).ready(function(){
    $("#p1").mouseenter(function(){
    alert("You entered p1!");
    });
    });
    </script>
    
    <p id="p1">Enter this paragraph.</p>

    mouseleave() The mouseleave() method attaches an event handler function to an HTML element.

    The function is executed when the mouse pointer leaves the HTML element:
    <script>
    $(document).ready(function(){
    $("#p1").mouseleave(function(){
    alert("Bye! You now leave p1!");
    });
    });
    </script>
    
    <p id="p1">This is a paragraph.</p>

    mousedown() The mousedown() method attaches an event handler function to an HTML element.

    The function is executed, when the left, middle or right mouse button is pressed down, while the mouse is over the HTML element:
    <script>
    $(document).ready(function(){
    $("#p1").mousedown(function(){
    alert("Mouse down over p1!");
    });
    });
    </script>
    
    <p id="p1">This is a paragraph.</p>

    mouseup() The mouseup() method attaches an event handler function to an HTML element.

    The function is executed, when the left, middle or right mouse button is released, while the mouse is over the HTML element:
    <script>
    $(document).ready(function(){
    $("#p1").mouseup(function(){
    alert("Mouse up over p1!");
    });
    });
    </script>
    
    <p id="p1">This is a paragraph.</p>

    hover() The hover() method takes two functions and is a combination of the mouseenter() and mouseleave() methods.

    The first function is executed when the mouse enters the HTML element, and the second function is executed when the mouse leaves the HTML element:
    <script>
    $(document).ready(function(){
    $("#p1").hover(function(){
    alert("You entered p1!");
    },
    function(){
    alert("Bye! You now leave p1!");
    }); 
    });
    </script>
    
    <p id="p1">This is a paragraph.</p>

    focus() The focus() method attaches an event handler function to an HTML form field.

    The function is executed when the form field gets focus:
    <script>
    $(document).ready(function(){
    $("input").focus(function(){
    $(this).css("background-color", "yellow");
    });
    $("input").blur(function(){
    $(this).css("background-color", "green");
    });
    });
    </script>
    
    Name: <input type="text" name="fullname"><br>
    Email: <input type="text" name="email">

    blur() The blur() method attaches an event handler function to an HTML form field.

    The function is executed when the form field loses focus:
    <script>
    $(document).ready(function(){
    $("input").focus(function(){
    $(this).css("background-color", "yellow");
    });
    $("input").blur(function(){
    $(this).css("background-color", "green");
    });
    });
    </script>
    
    Name: <input type="text" name="fullname"><br>
    Email: <input type="text" name="email">

    The on() Method The on() method attaches one or more event handlers for the selected elements.

    Attach a click event to a (p) element:
    <script>
    $(document).ready(function(){
    $("p").on("click", function(){
    $(this).hide();
    });
    });
    </script>
    
    <p>If you click on me, I will disappear.</p>
    <p>Click me away!</p>
    <p>Click me too!</p>

    Attach multiple event handlers to a (p) element:
    <script>
    $(document).ready(function(){
    $("p").on({
    mouseenter: function(){
        $(this).css("background-color", "lightgray");
    },  
    mouseleave: function(){
        $(this).css("background-color", "lightblue");
    }, 
    click: function(){
        $(this).css("background-color", "yellow");
    }  
    });
    });
    </script>
    
    <p>Click or move the mouse pointer over this paragraph.</p>


  6. jQuery Effects :

    jQuery hide() and show() With jQuery, you can hide and show HTML elements with the hide() and show() methods:
     <script>
    $(document).ready(function(){
    $("#hide").click(function(){
    $("p").hide();
    });
    $("#show").click(function(){
    $("p").show();
    });
    });
    </script>
    
    <p>If you click on the "Hide" button, I will disappear.</p>
    
    <button id="hide">Hide</button>
    <button id="show">Show</button>

    Syntax:
    $(selector).hide(speed,callback);
    
    $(selector).show(speed,callback);
    Note :- The optional speed parameter specifies the speed of the hiding/showing, and can take the following values: "slow", "fast", or milliseconds.

    The optional callback parameter is a function to be executed after the hide() or show() method completes

    jQuery toggle() You can also toggle between hiding and showing an element with the toggle() method.

    Shown elements are hidden and hidden elements are shown:
    <script>
    $(document).ready(function(){
    $("button").click(function(){
    $("p").toggle();
    });
    });
    </script>
    
    <button>Click Me!</button>            
    <p>This is Kaushal.</p>
    <p>from SpecBits.</p>

    Syntax :
    $(selector).toggle(speed,callback);
    Note :- The optional speed parameter can take the following values: "slow", "fast", or milliseconds.

    The optional callback parameter is a function to be executed after toggle() completes.

    jQuery Fading Methods With jQuery you can fade an element in and out of visibility.

    • fadeIn() The jQuery fadeIn() method is used to fade in a hidden element.

      Syntax :
      $(selector).fadeIn(speed,callback);
      Note :- The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.

      The optional callback parameter is a function to be executed after the fading completes.

      Example
      <script>
      $(document).ready(function(){
      $("button").click(function(){
      $("#div1").fadeIn();
      $("#div2").fadeIn("slow");
      $("#div3").fadeIn(3000);
      });
      });
      </script>
      
      <button>Click to fade in boxes</button><br><br>
      
      <div id="div1" style="width:80px;height:80px;display:none;background-color:red;"></div><br>
      <div id="div2" style="width:80px;height:80px;display:none;background-color:green;"></div><br>
      <div id="div3" style="width:80px;height:80px;display:none;background-color:blue;"></div>

    • fadeOut() The jQuery fadeOut() method is used to fade out a visible element.

      Syntax :
      $(selector).fadeOut(speed,callback);
      Note :- The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.

      The optional callback parameter is a function to be executed after the fading completes.

      Example
      <script>
      $(document).ready(function(){
      $("button").click(function(){
      $("#div1").fadeOut();
      $("#div2").fadeOut("slow");
      $("#div3").fadeOut(3000);
      });
      });
      </script>
      
      <button>Click to fade out boxes</button><br><br>
      
      <div id="div1" style="width:80px;height:80px;background-color:red;"></div><br>
      <div id="div2" style="width:80px;height:80px;background-color:green;"></div><br>
      <div id="div3" style="width:80px;height:80px;background-color:blue;"></div>

    • fadeToggle() The jQuery fadeToggle() method toggles between the fadeIn() and fadeOut() methods.

      If the elements are faded out, fadeToggle() will fade them in.

      If the elements are faded in, fadeToggle() will fade them out.

      Syntax :
      $(selector).fadeToggle(speed,callback);
      Note :- The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.

      The optional callback parameter is a function to be executed after the fading completes.

      Example
      <script>
      $(document).ready(function(){
      $("button").click(function(){
      $("#div1").fadeToggle();
      $("#div2").fadeToggle("slow");
      $("#div3").fadeToggle(3000);
      });
      });
      </script>
      
      <button>Click to fade in/out boxes</button><br><br>
      
      <div id="div1" style="width:80px;height:80px;background-color:red;"></div><br>
      <div id="div2" style="width:80px;height:80px;background-color:green;"></div><br>
      <div id="div3" style="width:80px;height:80px;background-color:blue;"></div>

    • fadeTo() The jQuery fadeTo() method allows fading to a given opacity (value between 0 and 1).

      Syntax :
      $(selector).fadeTo(speed,opacity,callback);
      Note :- The required speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.

      The required opacity parameter in the fadeTo() method specifies fading to a given opacity (value between 0 and 1).

      The optional callback parameter is a function to be executed after the function completes.

      Example
      <script>
      $(document).ready(function(){
      $("button").click(function(){
      $("#div1").fadeTo("slow", 0.15);
      $("#div2").fadeTo("slow", 0.4);
      $("#div3").fadeTo("slow", 0.7);
      });
      });
      </script>
      
      <button>Click to fade boxes</button><br><br>
      
      <div id="div1" style="width:80px;height:80px;background-color:red;"></div><br>
      <div id="div2" style="width:80px;height:80px;background-color:green;"></div><br>
      <div id="div3" style="width:80px;height:80px;background-color:blue;"></div>

    jQuery Sliding Methods With jQuery you can create a sliding effect on elements.

    • slideDown() The jQuery slideDown() method is used to slide down an element.

      Syntax :
      $(selector).slideDown(speed,callback);
      Note :- The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.

      The optional callback parameter is a function to be executed after the sliding completes.

      Example
      <script> 
      $(document).ready(function(){
      $("#flip").click(function(){
      $("#panel").slideDown("slow");
      });
      });
      </script>
                    
      <style> 
      #panel, #flip {
      padding: 5px;
      text-align: center;
      background-color: #e5eecc;
      border: solid 1px #c3c3c3;
      }
      
      #panel {
      padding: 50px;
      display: none;
      }
      </style>
      
      <div id="flip">Click to slide down panel</div>
      <div id="panel">This is Kaushal from SpecBits</div>

    • slideUp() The jQuery slideUp() method is used to slide up an element.

      Syntax :
      $(selector).slideUp(speed,callback);
      Note :- The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.

      The optional callback parameter is a function to be executed after the sliding completes.

      Example
      <script> 
      $(document).ready(function(){
      $("#flip").click(function(){
      $("#panel").slideUp("slow");
      });
      });
      </script>
      
      <style> 
      #panel, #flip {
      padding: 5px;
      text-align: center;
      background-color: #e5eecc;
      border: solid 1px #c3c3c3;
      }
      
      #panel {
      padding: 50px;
      }
      </style>
      
      <div id="flip">Click to slide up panel</div>
      <div id="panel">This is Kaushal from SpecBits</div>

    • slideToggle() he jQuery slideToggle() method toggles between the slideDown() and slideUp() methods.

      If the elements have been slid down, slideToggle() will slide them up.

      If the elements have been slid up, slideToggle() will slide them down.

      Syntax :
      $(selector).slideToggle(speed,callback);
      Note :- The optional speed parameter can take the following values: "slow", "fast", milliseconds.

      The optional callback parameter is a function to be executed after the sliding completes.

      Example
      <script> 
      $(document).ready(function(){
      $("#flip").click(function(){
      $("#panel").slideToggle("slow");
      });
      });
      </script>
      
      <style> 
      #panel, #flip {
      padding: 5px;
      text-align: center;
      background-color: #e5eecc;
      border: solid 1px #c3c3c3;
      }
      
      #panel {
      padding: 50px;
      display: none;
      }
      </style>
      
      <div id="flip">Click to slide the panel down or up</div>
      <div id="panel">This is Kaushal from SpecBits</div>

    Animation The jQuery animate() method is used to create custom animations.

    • jQuery Animations - The animate() Method The jQuery animate() method is used to create custom animations.

      Syntax :
      $(selector).animate({params},speed,callback);
      Note :- The required params parameter defines the CSS properties to be animated.

      The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.

      The optional callback parameter is a function to be executed after the animation completes.

      Example
      <script> 
      $(document).ready(function(){
      $("button").click(function(){
      $("div").animate({left: '250px'});
      });
      });
      </script>
      
      <button>Start Animation</button>
      
      <p>By default, all HTML elements have a static position, and cannot be moved.
      To manipulate the position, remember to first set the CSS position property of 
      the element to relative, fixed, or absolute!</p>
      
      <div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

    • jQuery animate() - Manipulate Multiple Properties

      Example
      <script> 
      $(document).ready(function(){
      $("button").click(function(){
      $("div").animate({
          left: '250px',
          opacity: '0.5',
          height: '150px',
          width: '150px'
      });
      });
      });
      </script>
      
      <button>Start Animation</button>
      
      <div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

    • jQuery animate() - Using Relative Values It is also possible to define relative values (the value is then relative to the element's current value). This is done by putting += or -= in front of the value:

      Example
      <script> 
      $(document).ready(function(){
      $("button").click(function(){
      $("div").animate({
          left: '250px',
          height: '+=150px',
          width: '+=150px'
      });
      });
      });
      </script>
      
      <button>Start Animation</button>
      
      <div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

    • jQuery animate() - Using Pre-defined Values You can even specify a property's animation value as "show", "hide", or "toggle":

      Example
      <script> 
      $(document).ready(function(){
      $("button").click(function(){
      $("div").animate({
      height: 'toggle'
      });
      });
      });
      </script>
      
      <p>Click the button multiple times to toggle the animation.</p>
      
      <button>Start Animation</button>
      
      <div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

    • jQuery animate() - Uses Queue Functionality By default, jQuery comes with queue functionality for animations.

      This means that if you write multiple animate() calls after each other, jQuery creates an "internal" queue with these method calls. Then it runs the animate calls ONE by ONE.

      So, if you want to perform different animations after each other, we take advantage of the queue functionality:

      Example
      <script> 
      $(document).ready(function(){
      $("button").click(function(){
      var div = $("div");
      div.animate({height: '300px', opacity: '0.4'}, "slow");
      div.animate({width: '300px', opacity: '0.8'}, "slow");
      div.animate({height: '100px', opacity: '0.4'}, "slow");
      div.animate({width: '100px', opacity: '0.8'}, "slow");
      });
      });
      </script>
      
      <button>Start Animation</button>
      
      <div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

    Stop Animations The jQuery stop() method is used to stop animations or effects before it is finished.

    • stop() The jQuery stop() method is used to stop an animation or effect before it is finished.

      The stop() method works for all jQuery effect functions, including sliding, fading and custom animations.

      Syntax :
      $(selector).stop(stopAll,goToEnd);
      Note :- The optional stopAll parameter specifies whether also the animation queue should be cleared or not. Default is false, which means that only the active animation will be stopped, allowing any queued animations to be performed afterwards.

      The optional goToEnd parameter specifies whether or not to complete the current animation immediately. Default is false.

      So, by default, the stop() method kills the current animation being performed on the selected element.

      Example
      <script> 
      $(document).ready(function(){
      $("#flip").click(function(){
      $("#panel").slideDown(5000);
      });
      $("#stop").click(function(){
      $("#panel").stop();
      });
      });
      </script>
      
      <style> 
      #panel, #flip {
      padding: 5px;
      font-size: 18px;
      text-align: center;
      background-color: #555;
      color: white;
      border: solid 1px #781717;
      border-radius: 3px;
      }
      
      #panel {
      padding: 50px;
      display: none;
      }
      </style>
      
      <button id="stop">Stop sliding</button>
      
      <div id="flip">Click to slide down panel</div>
      <div id="panel">Hello world!</div>

    jQuery Callback Functions A callback function is executed after the current effect is 100% finished.

    • jQuery Callback Functions JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors.

      To prevent this, you can create a callback function.

      A callback function is executed after the current effect is finished.

      Syntax :
      $(selector).hide(speed,callback);
      Note :- The optional stopAll parameter specifies whether also the animation queue should be cleared or not. Default is false, which means that only the active animation will be stopped, allowing any queued animations to be performed afterwards.

      The optional goToEnd parameter specifies whether or not to complete the current animation immediately. Default is false.

      So, by default, the stop() method kills the current animation being performed on the selected element.

      Example
      <script>
      $(document).ready(function(){
      $("button").click(function(){
      $("p").hide("slow", function(){
          alert("The paragraph is now hidden");
      });
      });
      });
      </script>
      
      <button>Hide</button>
      
      <p>This is a paragraph with little content.</p>

      Example without Callback
      <script>
      $(document).ready(function(){
      $("button").click(function(){
      $("p").hide(1000);
      alert("The paragraph is now hidden");
      });
      });
      </script>
      
      <button>Hide</button>
      
      <p>This is a paragraph with little content.</p>

    jQuery - Chaining With jQuery, you can chain together actions/methods.

    Chaining allows us to run multiple jQuery methods (on the same element) within a single statement.

    • jQuery Method Chaining Until now we have been writing jQuery statements one at a time (one after the other).

      However, there is a technique called chaining, that allows us to run multiple jQuery commands, one after the other, on the same element(s).

      Tip : This way, browsers do not have to find the same element(s) more than once.

      To chain an action, you simply append the action to the previous action.

      Example :
      <script>
      $(document).ready(function(){
      $("button").click(function(){
      $("#p1").css("color", "red").slideUp(2000).slideDown(2000);
      });
      });
      </script>
      
      <p id="p1">jQuery is fun!!</p>
      
      <button>Click me</button>
      Note :- We could also have added more method calls if needed.

      Tip : When chaining, the line of code could become quite long. However, jQuery is not very strict on the syntax; you can format it like you want, including line breaks and indentations.

      Example
      <script>
      $(document).ready(function(){
      $("button").click(function(){
      $("#p1").css("color", "red")
          .slideUp(2000)
          .slideDown(2000);
      });
      });
      </script>
      
      <p id="p1">jQuery is fun!!</p>
      
      <button>Click me</button>

  7. jQuery HTML

    • jQuery - Get Content and Attributes jQuery contains powerful methods for changing and manipulating HTML elements and attributes.

      jQuery DOM Manipulation One very important part of jQuery is the possibility to manipulate the DOM.

      jQuery comes with a bunch of DOM related methods that make it easy to access and manipulate elements and attributes.

      DOM = Document Object Model
      The DOM defines a standard for accessing HTML and XML documents:

      "The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."

      Get Content - text(), html(), and val()

      Three simple, but useful, jQuery methods for DOM manipulation are:
      text() - Sets or returns the text content of selected elements
      html() - Sets or returns the content of selected elements (including HTML markup)
      val() - Sets or returns the value of form fields

      How to get content with the jQuery text() and html() methods:

      Example :
      <script>
      $(document).ready(function(){
      $("#btn1").click(function(){
      alert("Text: " + $("#test").text());
      });
      $("#btn2").click(function(){
      alert("HTML: " + $("#test").html());
      });
      });
      </script>
      
      <p id="p1">jQuery is fun!!</p>
      
      <button>Click me</button>

      The value of an input field with the jQuery val() method:

      Example
      <script>
      $(document).ready(function(){
      $("button").click(function(){
      alert("Value: " + $("#test").val());
      });
      });
      </script>
      
      <p>Name: <input type="text" id="test" value="Mickey Mouse"></p>
      
      <button>Show Value</button>

      Get Attributes - attr() The jQuery attr() method is used to get attribute values.
      <script>
      $(document).ready(function(){
      $("button").click(function(){
      alert($("#w3s").attr("href"));
      });
      });
      </script>
              
      <p><a href="https://specbits.com" id="w3s">specbits.com</a></p>
      
      <button>Show href Value</button>

    • jQuery - Set Content and Attributes jQuery contains powerful methods for changing and manipulating HTML elements and attributes.

      How to set content with the jQuery text(), html(), and val() methods:

      Example :
      <script>
          $(document).ready(function(){
              $("#btn1").click(function(){
              $("#test1").text("Hello world!");
              });
              $("#btn2").click(function(){
              $("#test2").html("<b>Hello world!</b>");
              });
              $("#btn3").click(function(){
              $("#test3").val("Dolly Duck");
              });
          });
      </script>
      
          <p id="test1">This is a paragraph.</p>
          <p id="test2">This is another paragraph.</p>
      
          <p>Input field: <input type="text" id="test3" value="Mickey Mouse"></p>
      
          <button id="btn1">Set Text</button>
          <button id="btn2">Set HTML</button>
          <button id="btn3">Set Value</button>

      A Callback Function for text(), html(), and val()
      All of the three jQuery methods above: text(), html(), and val(), also come with a callback function. The callback function has two parameters: the index of the current element in the list of elements selected and the original (old) value. You then return the string you wish to use as the new value from the function.

      Example
      <script>
          $(document).ready(function(){
              $("#btn1").click(function(){
              $("#test1").text(function(i, origText){
                  return "Old text: " + origText + " New text: Hello world! (index: " + i + ")"; 
              });
              });
      
              $("#btn2").click(function(){
              $("#test2").html(function(i, origText){
                  return "Old html: " + origText + " New html: Hello <b>world!</b> (index: " + i + ")"; 
              });
              });
          });
      </script>
      
          <p id="test1">This is a <b>bold</b> paragraph.</p>
          <p id="test2">This is another <b>bold</b> paragraph.</p>
      
          <button id="btn1">Show Old/New Text</button>
          <button id="btn2">Show Old/New HTML</button>

      Set Attributes - attr() The jQuery attr() method is also used to set/change attribute values.
      <script>
          $(document).ready(function(){
              $("button").click(function(){
              $("#w3s").attr("href", "https://www.w3schools.com/jquery/");
              });
          });
      </script>
                      
          <p><a href="https://www.w3schools.com" id="w3s">W3Schools.com</a></p>
          
          <button>Change href Value</button>
      
          <p>Mouse over the link (or click on it) to see that the value of the href attribute has changed.</p>
      Note :- The attr() method also allows you to set multiple attributes at the same time.

    • jQuery - Add Elements With jQuery, it is easy to add new elements/content.

      Add New HTML Content
      append() - Inserts content at the end of the selected elements
      prepend() - Inserts content at the beginning of the selected elements
      after() - Inserts content after the selected elements
      before() - Inserts content before the selected elements

      jQuery append() Method : The jQuery append() method inserts content AT THE END of the selected HTML elements.
      <script>
      $(document).ready(function(){
      $("#btn1").click(function(){
      $("p").append(" <b>from SpecBits</b>.");
      });
      
      $("#btn2").click(function(){
      $("ol").append("<li> <b>List item ...</b> </li>");
      });
      });
      </script>
      
      <p>This is Kaushal</p>
      <p>This is another Developer</p>
      
      <ol>
      <li>List item 1</li>
      <li>List item 2</li>
      <li>List item 3</li>
      </ol>
      
      <button id="btn1">Append text</button>
      <button id="btn2">Append list items</button>

      jQuery prepend() Method The jQuery prepend() method inserts content AT THE BEGINNING of the selected HTML elements.
      <script>
      $(document).ready(function(){
      $("#btn1").click(function(){
      $("p").prepend("<b>This is kaushal</b> ");
      });
      $("#btn2").click(function(){
      $("ol").prepend("<li><b>List item ...</b></li>");
      });
      });
      </script>
      
      <p>from SpecBits.</p>
      <p>from DevelopersArmy.</p>
      
      <ol>
      <li>List item 1</li>
      <li>List item 2</li>
      <li>List item 3</li>
      </ol>
      
      <button id="btn1">Prepend text</button>
      <button id="btn2">Prepend list item</button>
      Note :- Add Several New Elements With append() and prepend()

      However, both the append() and prepend() methods can take an infinite number of new elements as parameters. The new elements can be generated with text/HTML (like we have done in the examples above), with jQuery, or with JavaScript code and DOM elements.



      jQuery after() and before() Methods The jQuery after() method inserts content AFTER the selected HTML elements.

      The jQuery before() method inserts content BEFORE the selected HTML elements.
      <script>
      $(document).ready(function(){
      $("#btn1").click(function(){
      $("img").before("<b>Before</b>");
      });
      
      $("#btn2").click(function(){
      $("img").after("<i>After</i>");
      });
      });
      </script>
                      
      <img src="copy-icon-vector-illustration.jpg" alt="jQuery" width="100" height="140"><br><br>
      
      <button id="btn1">Insert before</button>
      <button id="btn2">Insert after</button>
      Note :- Add Several New Elements With after() and before() Also, both the after() and before() methods can take an infinite number of new elements as parameters.

      The new elements can be generated with text/HTML (like we have done in the example above), with jQuery, or with JavaScript code and DOM elements.

    • jQuery - Remove Elements With jQuery, it is easy to remove existing HTML elements.

      Remove Elements/Content
      remove() - Removes the selected element (and its child elements)
      empty() - Removes the child elements from the selected element

      jQuery remove() Method : The jQuery remove() method removes the selected element(s) and its child elements.
      <script>
      $(document).ready(function () {
      $("button").click(function () {
      $("p").remove();
      });
      });
      </script>
      
      <div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">
      
      This is some text in the div.
      <p>This is a paragraph in the div.</p>
      <p>This is another paragraph in the div.</p>
      
      </div>
      <br>
      
      <button>Remove div element</button>

      jQuery empty() Method The jQuery empty() method removes the child elements of the selected element(s).
      <script>
      $(document).ready(function () {
      $("button").click(function () {
      $("p").empty();
      });
      });
      </script>
      
      <div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">
      
      This is some text in the div.
      <p>This is a paragraph in the div.</p>
      <p>This is another paragraph in the div.</p>
      
      </div>
      <br>
      
      <button>Empty the div element</button>
      Note :- Filter the Elements to be Removed

      The jQuery remove() method also accepts one parameter, which allows you to filter the elements to be removed.

      The parameter can be any of the jQuery selector syntaxes.

      $("p").remove(".test");

    • jQuery - Get and Set CSS Classes With jQuery, it is easy to manipulate the style of elements.

      jQuery Manipulating CSS
      addClass() - Adds one or more classes to the selected elements
      removeClass() - Removes one or more classes from the selected elements
      toggleClass() - Toggles between adding/removing classes from the selected elements
      css() - Sets or returns the style attribute

      jQuery addClass() Method :
      <script>
      $(document).ready(function () {
      $("button").click(function () {
      $("h1, h2, p").addClass("blue");
      $("div").addClass("important");
      });
      });
      </script>
      <style>
      .important {
      font-weight: bold;
      font-size: xx-large;
      }
      
      .blue {
      color: blue;
      }
      </style>
      
      <h1>Heading 1</h1>
      <h2>Heading 2</h2>
      
      <p>This is a paragraph.</p>
      <p>This is another paragraph.</p>
      
      <div>This is some important text!</div><br>
      
      <button>Add classes to elements</button>
      Note :- You can also specify multiple classes within the addClass() method:

      jQuery removeClass() Method How to remove a specific class attribute from different elements:
      <script>
      $(document).ready(function () {
      $("button").click(function () {
      $("h1, h2, p").removeClass("blue");
      });
      });
      </script>
      <style>
      .blue {
      color: blue;
      }
      </style>
      
      <h1 class="blue">Heading 1</h1>
      <h2 class="blue">Heading 2</h2>
      
      <p class="blue">This is a paragraph.</p>
      <p>This is another paragraph.</p>
      
      <button>Remove class from elements</button>

      jQuery toggleClass() Method How to use the jQuery toggleClass() method. This method toggles between adding/removing classes from the selected elements:
      <script>
      $(document).ready(function(){
      $("button").click(function(){
      $("h1, h2, p").toggleClass("blue");
      });
      });
      </script>
      <style>
      .blue {
      color: blue;
      }
      </style>
      
      <h1>Heading 1</h1>
      <h2>Heading 2</h2>
      
      <p>This is a paragraph.</p>
      <p>This is another paragraph.</p>
      
      <button>Toggle class</button>


    • jQuery - css() Method The css() method sets or returns one or more style properties for the selected elements.

      Syntax :
      css("propertyname");

      Set a CSS Property
      css("propertyname","value");

      Example
      <script>
      $(document).ready(function(){
      $("button").click(function(){
      $("p").css("background-color", "yellow");
      });
      });
      </script>
      
      <h2>This is a heading</h2>
      
      <p style="background-color:#ff0000">This is a paragraph.</p>
      <p style="background-color:#00ff00">This is a paragraph.</p>
      <p style="background-color:#0000ff">This is a paragraph.</p>
      
      <p>This is a paragraph.</p>
      
      <button>Set background-color of p</button>

      To set multiple CSS properties, use the following syntax:
      css({"propertyname":"value","propertyname":"value",...});