Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is jQuery?
2.1.
jQuery Example
3.
Need of Learning jQuery
4.
jQuery History
5.
Features of jQuery
6.
Applications of jQuery
7.
JQuery Selectors
7.1.
Example
7.1.1.
Selecting Elements by Name
7.1.2.
Selecting Elements by Id
7.1.3.
Selecting Elements by Class
8.
jQuery Methods
8.1.
Example
9.
jQuery Manipulation
10.
JQuery Traversing
10.1.
Example
11.
JQuery Events
11.1.
Example
12.
JQuery Effects
12.1.
Example
13.
JQuery AJAX
13.1.
Example
14.
Limitations of jQuery
15.
Advantages of jQuery
16.
Disadvantages of jQuery
17.
Frequently Asked Questions
17.1.
What is jquery and why is it used?
17.2.
What is bootstrap vs jQuery?
17.3.
How jQuery is used in JavaScript?
17.4.
What is the difference between JavaScript and jQuery?
18.
Conclusion
Last Updated: Mar 27, 2024
Medium

jQuery Introduction

gp-icon
Basics of Javascript
Free guided path
10 chapters
68+ problems
gp-badge
Earn badges and level up

Introduction

jQuery is an open-source library using which interaction with HTML/CSS documents is much easier than plain JavaScript. It shrinks the extended javascript code to a shorter one. Unlike HTML code, jQuery allows you to code various instructions quickly. 

Introduction to jQuery

What is jQuery?

JQuery is a very lightweight and compact Javascript library. It can run in various browsers and is cross-platform. It is popularly called "Write less, do more" because it performs many tasks in fewer lines of code than JavaScript. Simplifying complex JavaScript features, such as DOM manipulation and AJAX calls, is also beneficial.

The CDN link of jquery is given below:

<script src="https://code.jquery.com/jquery-3.6.4.slim.min.js" integrity="sha256-a2yjHM4jnF9f54xUQakjZGaqYs/V1CYvWpoqZzC2/Bw=" crossorigin="anonymous"></script>

jQuery Example

<!DOCTYPE html>
<html>
    <head> </head>
    <body>
        <h2>jQuery Example to hide the given two paragraphs</h2>
        <p>It is the first paragraph</p>
        <p>It is the second paragraph</p>
        <button class="btn">hide</button>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
              $("button").click(function(){
                $("p").hide();
              });
            });
        </script>
    </body>
</html>

 

In the example above, there are two paragraphs along with a “hide” button. When you click the hide button, both paragraphs will hide and will not be visible. This simple example shows how jQuery so quickly and with fewer lines of code performs the task compared to JavaScript.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Need of Learning jQuery

The major needs of jQuery are discussed below:

  • Using jQuery, the selection of DOM elements is much more accessible.
  • Jquery is needed to achieve cross-browser compatibility, which means that the code of jQuery can work fine on all browsers.
  • Most developers use jQuery to make web pages more interactive, and user-friendly in their project development. jQuery has many built-in animation effects hence using them, you can create responsive and highly featured websites.
  • jQuery is more SEO friendly because of the presence of unique descriptions and titles and permanent descriptive links separated by dashes.

jQuery History

jQuery was first given to developers in January 2006, made by John Resig at BarCamp NYC. It is headed by Timmy Wilson currently, and a team of developers works on its maintenance. Nowadays, jQuery is one of the widely used technologies. Most websites use jQuery.

Version number  Delivered Date
1.0 26 August 2006
1.1 14 January 2007
1.2 10  September 2007
1.3 14 January 2009
1.4 14 January 2010
1.5 31 January 2011
1.6 3 May 2011
1.7 3 November 2011
1.8 9 August 2012
1.9 15 January 2013
1.10 24 May 2013
1.11 24 January 2014
2.0 18 April 2013
2.1 24 January 2014

Features of jQuery

A list of features of jQuery is given below:

  • jQuery has a relatively small size, whose compressed version is around 90kb.
  • jQuery is a friendly-to-use library. Most web designers already know it uses CSS in its structured code.
  • jQuery is globally tried and tested because many popular websites use jQuery, like Digg, Dell, Onion, and NBC.
  • jQuery has a vast developer community; hence many people work together on jQuery projects to write code, fix errors and provide necessary modifications.
  • jQuery lets the coders create plug-ins and some other javascript programs that work along with jQuery to enhance the code and provide extra functionalities.

Applications of jQuery

The significant applications of jQuery are discussed below:

  • It can be used to create reusable, clear, and simple code.
  • In web applications, it adds Ajax functionality, manages events and executes animation.
  • Jquery's cross-browser open-source Sizzle selector engine makes it simple to choose DOM elements, negotiate with them, and modify them.
  • By offering a collection of straightforward methods and selectors, jQuery makes it easier to access, manipulate, and navigate within the Document Object Model (DOM).
  • With jQuery, handling browser events like clicks, hovers, submits, etc., is easy and effective.

JQuery Selectors

It is the most used functionality of jQuery. jQuery helps grab the HTML element you have to perform your task. It just selects an element, and the work is done on it accordingly.

The jQuery selectors are basically of three types which are discussed below:

Selectors

Description

Tag Name It selects an element by its tag name; for example, if you want to select all the <span> tags.
Tag Class It is used to select an element by its assigned class name; for example, if you want to choose an element with the class name “paragraph1” you can use $(‘.paragraph1’)
Tag ID It is used to select an element by its unique id given to it; for example, if you want to choose an element with the id “para1” you can use $(‘#para1’)

 

Example

Selecting Elements by Name

$(document).ready(function () {
  $("span").css("background", "blue");
});

Selecting Elements by Id

$(document).ready(function () {
  $("#para1").css("background", “red");
});

Selecting Elements by Class

$(document).ready(function () {
  $(".paragraph1").css("background", "green");
});

jQuery Methods

Using jQuery methods, you can perform many essential activities that require many lines of JavaScript code.

The various categories of methods are given below.

Methods

Description

Important Methods

DOM Manipulation The methods in this category change the attributes and styles of DOM elements and add and remove features, among other things.

after(),append(),attr(),before()

 

Traversing These methods facilitate moving from one DOM element to another in a parent-child hierarchy, such as locating an element's ancestors, descendants, or siblings.

children(),closest(),

each(),first(),next(),

filter(),parent(),

siblings()

 

CSS These methods get and set CSS-related properties of elements.

addClass(),css(),

hasClass(),

removeClass(),

toggleClass()

 

Attributes These methods let you get and change an element's DOM characteristics.

attr(), html(),

removeAttr(), prop(),

val(),

 

Events To handle DOM or JavaScript events, utilise these methods.

bind(), blur(), change(), click(), dblclick(), focus(),

keyup(), keydown()

 

Effects These techniques are used to give elements animation.

animate(), fadeIn(),

fadeOut(), hide(),

show(), stop()

 

Ajax These methods allow Ajax functionalities with jQuery e.g.

get(), getJson(),

post(), load(),

 

 

Example

<!DOCTYPE html>
<html>
    <head> </head>
    <body>
        <h2>jQuery Example for methods</h2>
        <p></p>
        <!-- the content in these elements will be inserted using jquery methods-->
        <span></span>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
        <script>
            $(document).ready(function(){


             $('p').append("This is a paragraph"); //It appends the given text to 'p'
             $('span').before('<p>This is another paragraph </p>'); //It inserts a new paragraph before span


            });
        </script>
    </body>
</html>

jQuery Manipulation

jQuery offers a variety of effective DOM manipulation techniques.

It provides a clean and concise code for obtaining or setting the content of any HTML element.

Some of the fundamental operations of jQuery functions are:

  • Extracting the content of the element
  • Altering an element's content
  • Placing a new element as a child of a current element
  • Putting a parent element on top of a current element
  • Preceding or following an existing component with a new element
  • Replace a present part with a new one.

 

jQuery Manipulation types are discussed below:

jQuery Manipulation
  • Getters: It gets or reads the value of the element. No arguments are passed in these methods. For extracting the content of the matching HTML element, jQuery offers the html() and text() functions.

The syntax for these two procedures, when they are used to get the values, is as follows:

$(selector).html();

$(selector).text();

text(): The text of the selected elements can be changed or returned using this function.

html(): It sets or retrieves the HTML contents of the elements.

  • Setters: It sets or assigns the value to the element. Arguments are passed when using these functions. The content of the matching HTML element can be developed using the jQuery text() and html() procedures. 

The syntax for these two procedures, when they are used to set the values, is as follows:

$(selector).html(value, [function]);

$(selector).text(value, [function]);

Here, "value" denotes content that will be inserted into the element. These methods can accept an optional callback function that will be fired when the element's value is set.

JQuery Traversing

A method for finding (or choosing) HTML components based on their connections to other elements is called jQuery traversing. 

JQuery traversing makes it simple to move up (ancestors), down (descendants), and laterally (siblings) in the tree, starting with the currently selected (current) element. 

Some of the traversing methods are:

Methods Description Syntax
add() By using this function, a new jQuery object is created and added to the requested elements. $(selector).add(element,context)
addBack() adds an initial set of elements from the jQuery library to the current stack element. $(selector).addBack(selector)
children() This method finds the child element of each specified element. $(selector).children(filter)
closest() It is used to find the element which matches first to the selector. $(selector).closest(filter)
end() This method ends the most recent filtering task and its matched element is sent to its previous state. $(selector).end()
filter() This method reduces the set of the selected element to one at the specified index. $(selector).filter(criteria,function(index))
first() This method gives specified elements based on the selector provided. $(selector).first()

Example

<!DOCTYPE html>
<html>
    <head>
        <style>
            .background-highlight {
                background: grey;
                color: red;
            }
        </style>
    </head>
    <body>
        <h1>jquery example for methods</h1>
        <ul>
            <li>First list item</li>
            <li>Second list item</li>
            <li>Third list item</li>
            <li>Last list item</li>
        </ul>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
               //It will add CSS properties of the background-highlight class to the list of elements coming at odd positions (0-based indexing)
                           $("ul li").filter(":odd").addClass("background-highlight");
                       });
        </script>
    </body>
</html>

JQuery Events

An event is a user-performed activity, such as mouse or keyboard clicking. An instance of an event might be when someone clicks the submit button on a form, the page loads and the data is erased. Event handling is the process of responding to these occurrences. Some of the jQuery events are shown below:

Events  Description  Syntax
click() It will execute the function whenever any click event occurs. $(selector).click(function);
hover() Using this, you can change the content of any element whenever the cursor comes over it. $(selector).hover(function);
blur() It reduces the focus on the selected elements. $(selector).blur(function);
on() It can add more than one event handler to the selected elements. $(selector).on(event, childSelector, data, function)

Example

<!DOCTYPE html>
<html>
    <head>
        <style>
            .background-highlight {
                background: grey;
                color: red;
            }
        </style>
    </head>
    <body>
        <h1>Example jquery Events</h1>
        <p>Hover on this the paragraph to see the event</p>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
        <script>
              $(document).ready(function(){
                $("p").hover(function(){
                    $(this).addClass("background-highlight");
                }, function(){
                    $(this).removeClass("background-highlight");
                });
            });
        </script>
    </body>
</html>

JQuery Effects

We can apply effects to a web page using jQuery.When designing websites, jQuery effects provide extra beauty to them. It increases efficiency and simplifies creating web pages with different effects and animations.

You may add several effects, including hide/show, fade, slide, animate, toggle, and many more. Simple, widely-used effects can be added using jQuery, and you can also develop your custom effects.

Some of the methods of jQuery effects are as follows::

Effects Description Syntax
animate() On the elements you choose, you may utilize them to run custom animations.

$(selector).animate({styles},speed,easing,callback) 

 

delay() The execution of all queued functions on the chosen items is postponed using this technique. $(selector).delay(speed,queueName) 
fadeIn() It gradually brings in the chosen elements. $(selector).fadeIn()
finish() All animation in the queue for the chosen elements will stop, delete, and finish. $(selector).finish(queueName)
slideDown() displays the matched components on a slide. $(selector).slideDown(speed,callback)
toggle() reveals or conceals the items that match. It switches back and forth between the show() and hide() functions.

$(selector).toggle(function)

 

stop() the animation that is playing on the matched items is stopped. $(selector).stop(stopAll,goToEnd)

 

Example

<!DOCTYPE html>
<html>
    <head>
        <style>
            .background-highlight {
                background: grey;
                color: red;
                width: 100px;
                height: 100px;
            }
        </style>
    </head>
    <body>
        <h1>jquery example for methods</h1>
        <p class="background-highlight"></p>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
        <script>
                $(document).ready(function() {

                $("p").animate({fontSize:"20px" ,
                   height: "350px",
                   width: "350px",
                   opacity: 0.7
            }, 1200);
            });
        </script>
    </body>
</html>

JQuery AJAX

Asynchronous JavaScript and XML, or Ajax, is a method of updating a web page without refreshing the whole thing. It will send and receive data from the server in the background.

Ajax's underlying technologies are quite complex. They combine the functions of JavaScript, server-side scripting, and the web browser.

With the aid of Ajax technologies, you may accomplish a lot of straightforward tasks:

  • It displays entirely new content without reloading the page.
  • As soon as you submit a form, it instantly displays the results.
  • Whenever you hit the sign-in button, you are not only logged in, but the page also transforms to show.
  • Ajax provides navigation of database records without switching to any other page.

Given below is a list of jQuery Ajax methods.

Methods Description Syntax
$.load() Fetches some HTML from the server and inserts it into the element’s DOM. $(selector).load(url,data,function(response,status,xhr))+
$.getScript() Utilises an AJAX HTTP GET request to run a JavaScript script from a server. $.getScript(url);
$.ajaxPrefilter() This function filters all AJAX calls before they are sent to the server. $.ajaxPrefilter([ data_types], handler);
$.ajaxSetup() It can be used to set options for all AJAX calls. $.ajaxSetup({name:value, name:value, ... })
$.ajaxSuccess() It triggers the ajaxSuccess event when an Ajax request completes successfully. $(document).ajaxSuccess(function(event,xhr,options))
$.ajaxComplete() It triggers the ajaxComplete event when the Ajax request completes. $(document).ajaxComplete(function(event, xhr, options))
$.ajaxError() It triggers the ajaxError event when an Ajax request completes with an error. $(document).ajaxError(function(event,xhr,options,exc))
$.post() It loads data from a server using an AJAX HTTP POST request. $.post(url,[data],[callback],[type])

Example

<!DOCTYPE html>
<html>
    <head>
        <title>jQuery ajax() Method</title>
    </head>


    <body style="text-align: center">
        <h3>Example of jQuery ajax() Method</h3>


        <h3 id="h11"></h3>


        <button>Click to get the content</button>


        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <!-- This script uses ajax() to add the text content to the website from a local file stored in the computer-->
        <script>
            $(document).ready(function() {
             $("button").click(function() {
             $.ajax({url: "localTextFile.txt",
             success: function(result) {
             $("#h11").html(result);
             }});
             });
            });
        </script>
    </body>
</html>
  • Output before clicking the button
Output


 

  • Output after clicking the button
     
Output

Limitations of jQuery

The significant limitations of jquery are discussed below:

  • Much of jQuery code depends on javascript; hence it will not work correctly if the user's browser does not support JavaScript.
  • The file size of jQuery is large, which might increase the load time of the websites and software programs using it.
  • Web components, becoming increasingly common in web development, cannot be used with jQuery.
  • Many advanced frameworks are present in the market with which jQuery is incompatible.

Advantages of jQuery

The following are the advantages of utilizing jQuery as opposed to writing your code in pure Javascript:

Advantages of jQuery
  • Easy to code: JQuery has an intuitive structure that makes it straightforward to use. 
  • Integrating different IDEs is simple: jQuery is an open-source library supported entirely in other IDEs. Microsoft's 2010 release of the Visual Studio IDE now officially supports jQuery. Effects and animation JQuery provides engaging animations and effects for your website by fusing CSS, AJAX, JavaScript, and HTML.
  • Animation and effects: JQuery utilizes a combination of CSS, AJAX, JavaScript, and HTML, providing cool animations and effects for your website.
  • Fast: This enables you to write your code fast as compared to plain JavaScript.
  • SEO Friendly: There are many plug-ins available for jQuery that can assist developers in search engine optimization. Using unordered lists in jQuery elements is one of the SEO-friendly techniques. 
  • Cross-Browser Compatibility: jQuery solves most of these cross-browser problems because it helps to create a website that will work properly across all browser kinds and versions.

Disadvantages of jQuery

Jquery offers numerous benefits, but it also has certain drawbacks, some of which are as follows:

  • Limited Functionality: jQuery is slower to code in larger apps than PHP or ASP.NET. You desire another application to deliver your expertise (such as an online service) created in a different language (such as .NET, Java, or PHP). You must have to become familiar with CSS and how it functions. A bit difficult to debug.
  • JQuery javascript file required to run jquery commands: Page load time can increase with more JavaScript files on a website. The numerous capabilities and plugins that jQuery provides can result in bigger file sizes. Usage of jQuery increases the reliance on the third-party library, hence increasing the risk of a security breach and complicating the updation and maintenance of code.

Frequently Asked Questions

What is jquery and why is it used?

jQuery is a JavaScript library that makes JavaScript writing more uncomplicated and enjoyable. The reading and manipulation of HTML DOM elements are easier. Handling events, creating animations, and making AJAX requests are some of the major functionalities of jQuery. Additionally, it complies with the MIT Licence and is free, open-source software. Finally, the jQuery library is modular, so programmers may build sophisticated dynamic web pages and apps. 

What is bootstrap vs jQuery?

Bootstrap is mainly used to make the website appear suitable using HTML and CSS. It helps make responsive web-pages. While jQuery UI helps ease the JavaScript backend process. It contains a user interface counterpart of its own.

How jQuery is used in JavaScript?

jQuery is a lightweight JavaScript library. It makes it easier to write and use JavaScript on the website. jQuery requires JavaScript code. It connects dynamically-applied JavaScript behaviors as well as attributes, simplifying client-side scripting.

What is the difference between JavaScript and jQuery?

The main difference is that while jQuery is a lightweight JavaScript library, it cannot exist on its own; it depends on JavaScript. At the same time, JavaScript is an independent programming language. But jQuery uses fewer lines of code than JavaScript.

Refer to know about:   jquery ajax

Conclusion

A well-known JavaScript library called jQuery makes creating web applications easier and faster. It offers many tools and functionalities that aid programmers in producing clear, concise, cross-browser-compatible code. In this article, we have discussed a brief introduction to jQuery, jQuery history, features, and methods. In addition, several benefits and drawbacks are also shown.

Web development today uses more modern JavaScript frameworks and libraries like React, Angular, and Vue rather than the once-popular jQuery. However, jQuery is still useful for small to medium-sized projects and older systems that need backward compatibility in web development. Overall, jQuery continues to be a vital and valuable tool for developers to increase productivity and build dynamic and interactive online apps.

Next article
Jquery AJAX
Guided path
Free
gridgp-icon
Basics of Javascript
10 chapters
68+ Problems
gp-badge
Earn badges and level up
Live masterclass