JQuery Notes
JQuery Notes
• jQuery is a lightweight JavaScript library which is blazing fast and concise. This library was created
by John Resig in 2006 and jQuery has been designed to simplify HTML DOM tree traversal and
manipulation, as well as event handling, CSS animation, and Ajax.
• The motto to create jQuery is: Write less, do more. jQuery simplifies HTML document traversing,
event handling, animating and Ajax interactions for rapid web development.
• jQuery can be used to find a particular HTML element in the HTML document with a certain ID,
class or attribute and later we can use jQuery to change one or more of attributes of the same
element like color, visibility etc. jQuery can also be used to make a webpage interactive by
responding to an event like a mouse click.
• jQuery is free, open-source software which comes under the permissive MIT License. As of Apr
2021, jQuery is used by 77.8% of the top 10 million most popular websites.
• Before you start learning jQuery, you should have basic understanding of HTML, CSS and
JavaScript, Document Object Model (DOM).
jQuery Advantages
• DOM manipulation – the jQuery made it easy to select DOM elements, and modifying their
content by using cross-browser open-source selector engine called Sizzle.
• Event Handling – The jQuery offers to capture a wide variety of events, such as a user clicking on
a link, without the need to large HTML code itself with event handlers.
• AJAX Support – The jQuery helps you a lot to develop a responsive and feature rich site using
AJAX technology.
• Animations – The jQuery comes with plenty of built – in animation effects which you can use in
your websites.
• Lightweight – The jQuery is very lightweight library – about 19KB in size (Minified and gzipped).
• Cross Browser support – The jQuery has cross browser support, and works well in IE 6.0+, FF 2.0+,
Safari 3.0+, Chrome and Opera 9.0+.
• Latest Technology – The jQuery supports CSS3 selectors and basic XPath syntax.
Setting up jQuery
Local Installation
• You can download latest version of jQuery on your web browser and include the downloaded
library in your code. We should use the compressed version of the library for a better performance.
• Go to the https://jquery.com/download/ to download the latest version available.
• Now put the downloaded jquery-3.7.1.min.js file in a directory of your website. e.g. js/jquery-
3.7.1.js
• Finally include this jQuery file into your HTML markup file.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="./js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
document.write("Hello, World!");
});
</script>
</head>
<body>
<!-- HTML body goes here -->
</body>
</html>
CDN based Installation
• You can include jQuery library into your HTML code directly from a Content Delivery Network
(CDN).
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js">
</script>
<script>
$(document).ready(function() {
document.write("Hello, World!");
});
</script>
</head>
<body>
<!-- HTML body goes here -->
</body>
</html>
How to call a jQuery Library functions?
• We want to add the jQuery code when the Document Object Model (DOM) is ready. So if we want
an event to work on the page, we can call it inside the $(document).ready() function. Everything
inside it will load as soon as the DOM is loaded and before the page contents are loaded.
$(document).ready(function() {
// do stuff when DOM is ready
});
• Following example will show the use of jQuery and while clicking on div the given code will run.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="./js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function() {alert("Hello, world!");});
});
</script>
</head>
<body>
<div>Click on this to see a dialogue box.</div>
</body>
</html>
• String : A string in JavaScript (jQuery) is an immutable object that contains none, one or many
characters. Following are the valid examples of a JavaScript String −
5350
120.27
0.26
• Boolean : A Boolean in JavaScript (jQuery) can be either true or false. If the number is zero, it
defaults to false. If an empty string defaults to zero.
true // true
false // false
0 // false
1 // true
"" // false
"hello" // true
• Objects : JavaScript (jQuery) supports Object concept very well. You can create an object using the
object literal as follows.
var emp = {
name: "Parul",
age: 16
};
• You can write and read properties of an object using the dot notation as follows –
function named(){
// do some stuff here
}
• An anonymous function can be defined in similar ways as a normal function but it would not have
any name. A anonymous function can be assigned to a variable or passed to a method as below.
$(document).ready(function (){
//do some stuff here
});
• Arguments : JavaScript (jQuery) variable arguments is a kind of array which has length property.
function func(x){
console.log(typeof x, arguments.length);
}
$(document).ready(function() {
// this refers to window.document
});
$("div").click(function() {
// this refers to a div DOM element
});
• You can specify the context for a function call using the function-built-in methods call() and apply()
methods.
• The difference between them is how they pass arguments. Call passes all arguments through as
arguments to the function, while apply accepts an array as a argument.
function scope() {
console.log(this, arguments.length);
}
scope() // window, 0
scope.call("foobar", [1,2]); //==> "foobar", 1
scope.apply("foobar", [1,2]); //==> "foobar", 2
• Scope : The scope of a variable is the region of your program in which it is defined. JavaScript
(jQuery) variable will have only two scopes.
o Global Variables – A global variable has global scope which means it is defined everywhere
in your javascript code.
o Local Variables - A local variable will be visible only within a function where it is defined.
Function parameters are always local to the function.
• Within the body of a function, a local variable takes precedence over a global variable with having
same name.
function ( ) {
var myVar = "local"; // ==> Declare a local variable
document.write(myVar); // ==> local
}
The Document Object Model (DOM)
<html>
<head>
<title>The DOM Example</title>
</head>
<body>
<div>
<p>This is a paragraph.</p>
<p>This is second paragraph.</p>
<p>This is third paragraph.</p>
</div>
</body>
</html>
• Following are main points for above tree structure.
• The <html> is an root tag of all other elements.
• The <head> and <body> are children of <html>.
• The <p> are children of <div>, and <div> is children of <body>.
• Actually, before we execute any jQuery statement, we would like to wait for the document to be
fully loaded. This is because jQuery works on DOM and if complete DOM is not available before
executing jQuery statements, then we will not get desired result.
• Following is a syntax of Document Ready Event:
$(document).ready(function(){
});
• Alternatively, you can also use the following syntax for document ready event.
$((function(){
});
Always keep above Document Ready Event function into <script>…</script> tag. And you can keep
<script> tag inside <head> section or at the closing tag of the <body>.
jQuery Syntax
• Following is the basic syntax for selecting HTML elements and then performing some action on the
selected element(s):
$(document).ready(function(){
$(selector).action()
});
• Any jQuery statement starts with a dollar sign ($) and then we put a selector inside the braces().
• This syntax $(selector) is enough to return the selected HTML elements, but if you have to perform
any action on the selected element(s) then action() part is required.
• E.g. here select all <p> elements from an HTML document and will hide those elements.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.js"></script>
<script>
$(document).ready(function() {
$("p").hide()
});
</script>
</head>
<body>
<h1>jQuery Basic Syntax</h1>
<p>This is p tag</p>
<p>This is another p tag</p>
<span>This is span tag</span>
<div>This is div tag</div>
</body>
</html>
• Let's re-write the above example using jQuery() method instead of $():
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.js"></script>
<script>
$(document).ready(function() {
jQuery("p").hide()
});
</script>
</head>
<body>
<h1>jQuery Basic Syntax</h1>
<p>This is p tag</p>
<p>This is another p tag</p>
<span>This is span tag</span>
<div>This is div tag</div>
</body>
</html>
• E.g. jQuery to change the color of all the <h1> elements to red.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("h1").css("color", "red")
});
</script>
</head>
<body>
<h1>jQuery Basic Syntax</h1>
<p>This is p tag</p>
<span>This is span tag</span>
<div>This is div tag</div>
</body>
</html>
• E.g. jQuery to change the color of all the elements whose class is red.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$(".red").css("color", "red")
});
</script>
</head>
<body>
<h1>jQuery Basic Syntax</h1>
<p>This is p tag</p>
<span>This is span tag</span>
<div class="red">This is div tag</div>
</body>
</html>
jQuery Selector
• jQuery selectors are used to select HTML elements from an HTML document. jQuery selectors can
find HTML elements based on the following:
o HTML element Name
o Element ID
o Element Class
o Element attribute name
o Element attribute value
$(document).ready(function(){
$(selector)
});
• A jQuery selector starts with a dollar sign $ and we put a selector inside the braces (). Here $() is
called factory function, which makes use of following three blocks while selecting elements in a
given document.
• The element selector: It represents an HTML element name available in the DOM. E.g., $('p')
selects all paragraph <p> in the document.
$(document).ready(function(){
$("Html Element Name")
});
• E.g. Here, selector will select all the <p> elements from an HTML Dodument and then change the
background of these paragraphs.
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("p").css("background-color", "yellow");
});
</script>
</head>
<body>
<h1>jQuery element Selector</h1>
<p>This is p tag</p>
<span>This is span tag</span>
<div>This is div tag</div>
</body>
</html>
• The #ID Selector: It represents HTML element available with given ID in the DOM. E.g. $('#some-
id') selects the single element in the document that has some-id as element ID. When you use ID
then it should be unique to all the DOM elements.
$(document).ready(function(){
$("#id of the element")
});
• E.g., Here, the code select the <p> element whose id is foo and change the background color of
those paragraphs.
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("#foo").css("background-color", "yellow");
});
</script>
</head>
<body>
<h1>jQuery #id Selector</h1>
$(document).ready(function(){
$(".class of the element")
});
• E.g., Here, the code select all those elements whose class is foo and change the background color
of those elements.
<html>
<head>
<title>The jQuery Example</title>
<script src = "js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$(".foo").css("background-color", "yellow");
}
);
</script>
</head>
<body>
<h1>jQuery .class Selector</h1>
<p class="foo">This is foo p tag</p>
<p class="foo">This is one more foo p tag</p>
<span class="bar">This is bar span tag</span>
<div class="bill">This is bill div tag</div>
</body>
</html>
jQuery Events
• Any modern web application can't be imagined without an event associated with it. Events are the
mechanism to build an interactive web page. jQuery is smart enough to handle any event
generated on an HTML page.
• A jQuery Event is the result of an action that can be detected by jQuery (JavaScript). When these
events are triggered, you can then use a custom function to do pretty much whatever you want
with the event. These custom functions are called Event Handlers.
• The jQuery library provides methods to handle all the DOM events and make complete event
handling considerably easier than what we have available in JavaScript.
• Most common events are a mouse click, a webpage loading, taking mouse over an element,
submitting an HTML form, a keystroke on a keyboard.
• Mouse events
• Click, dblclick, hover, mousedown, mouseup
• Keyboard events
• Keypress, keydown, keyup
• Form events
• Submit, change, select, blur, focusin
• Document Events
• Load, resize, scroll, unload, ready.
• When you want to click a <div> in an HTML document and then you want to perform some action
against this click. To achieve this you will have to bind a jQuery click event with the <div> element
and then define an action against the click event.
• Following is jQuery syntax to bind a click event with all the <div> elements available in an HTML
document:
$("div").click();
• The next step is to define an action against the click event. Following is the syntax to define a
function which will be executed when click event will be fired. This function is called jQuery Event
Handler.
$("div").click(function(){
//jQuery code goes here
});
• Following is another syntax to bind a click event with any of the DOM elements:
$("div").bind('click',function(){
//jQuery code goes here
});
jQuery click Event
• To bind a click event with <div> where an alert box is displayed whenever you click on any of the
divs.
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function(){
alert('Hi there!');
});
});
</script>
<style>
div{ margin:10px;padding:12px; border:2px solid #666;
width:60px;cursor:pointer}
</style>
</head>
<body>
<p>Click on any of the squares to see the result:</p>
<div>One</div>
<div>Two</div>
<div>Three</div>
</body>
</html>
jQuery dblclick Event
• Let’s implement the dblclick event with <div> where an alert box is displayed whenever we double
click on any of the divs.
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("div").dblclick(function(){
alert('Hi there!');
});
});
</script>
<style>
div{ margin:10px;padding:12px; border:2px solid #666;
width:60px;cursor:pointer}
</style>
</head>
<body>
<p>Double click on any of the squares to see the result:</p>
<div>One</div>
<div>Two</div>
<div>Three</div>
</body>
</html>
jQuery mouseenter event
• Here, we can bind mouseenter event with <div> where an alert box is displayed when you bring
cursor over any of the divs
<html>
<head>
<title>The jQuery Example</title>
<script
src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("div").mouseenter(function(){
alert('Cursor is in!');
});
});
</script>
<style>
div{ margin:10px;padding:12px; border:2px solid #666;
width:60px;cursor:pointer}
</style>
</head>
<body>
<p>Bring cursor over any of the squares to see the result:</p>
<div>One</div>
<div>Two</div>
<div>Three</div>
</body>
</html>
jQuery mouseleave event
• Here, we can bind mouseleave event with <div> where an alert box is displayed when you takeout
the cursor from any of the divs.
<html>
<head>
<title>The jQuery Example</title>
<script
src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("div").mouseleave(function(){
alert('Cursor is out!');
});
});
</script>
<style>
div{ margin:10px;padding:12px; border:2px solid #666;
width:60px;cursor:pointer}
</style>
</head>
<body>
<p>Bring cursor out any of the squares to see the result:</p>
<div>One</div>
<div>Two</div>
<div>Three</div>
</body>
</html>
jQuery mousedown event
• Here, we can bind mousedown event with <div> where an alert box is displayed when you pressed
down any of the mouse button over any of the divs.
<html>
<head>
<title>The jQuery Example</title>
<script
src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("div").mousedown(function(){
alert('Mouse button is down!');
});
});
</script>
<style>
div{ margin:10px;padding:12px; border:2px solid #666;
width:60px;cursor:pointer}
</style>
</head>
<body>
<p> Press mouse button down over any of the squares to see the
result:</p>
<div>One</div>
<div>Two</div>
<div>Three</div>
</body>
</html>
jQuery mouseup event
• Here, we can bind mouseup event with <div> where an alert box is displayed when any of the
mouse button is release over any of the divs.
<html>
<head>
<title>The jQuery Example</title>
<script
src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("div").mouseup(function(){
alert('Mouse button is released!');
});
});
</script>
<style>
div{ margin:10px;padding:12px; border:2px solid #666;
width:60px;cursor:pointer}
</style>
</head>
<body>
<p> Release mouse button down over any of the squares to see the
result:</p>
<div>One</div>
<div>Two</div>
<div>Three</div>
</body>
</html>
jQuery Event Object
• Whenever a jQuery event is fired, jQuery passes an Event Object to every event handler
function. The event object provides various useful information about the event. The event object
is needed to handle some of the situation when handler is needed.
• Following are the properties / attributes which are available and safe to access.
Properties Description
altKey Set to true if the Alt key was pressed when the event was triggered, false if not.
ctrlKey Set to true if the Ctrl key was pressed when the event was triggered, false if not.
data The value, if any, passed as the second parameter to the bind() command when the
handle was established.
keyCode For keyup and keydown events, this returns the key that was pressed.
metaKey Set to true if the Meta key was pressed when the event was triggered, false it not.
pageX For mouse events, specifies the horizontal coordinate of the event relative from the
page origin.
pageY For mouse events, specifies the vertical coordinate of the event relative from the
page origin.
screen For mouse events, specifies the horizontal coordinate of the event relative from the
screen origin.
screenY For mouse events, specifies the vertical coordinate of the event relative from the
screen origin.
shiftKey Set to true if the Shift key was pressed when the event was triggered, false if not.
target Identifies the element for which the event was triggered.
timeStamp The timestamp (in milliseconds) when the event was triggered.
type For all events, specifies the type of event that was triggered (e.g. click).
which For keyboard events, specifies the numeric code for the key that caused the event,
and for mouse events, specifies which button was pressed (1 for left, 2 for middle, 3
for right)
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function(eventObj){
alert('Event type is ' + eventObj.type);
alert('pageX : ' + eventObj.pageX);
alert('pageY : ' + eventObj.pageY);
alert('Target : ' + eventObj.target.innerHTML);
});
});
</script>
<style>
div{ margin:10px;padding:12px; border:2px solid #666;
width:60px;cursor:pointer}
</style>
</head>
<body>
<p>Click on any of the squares to see the result:</p>
<div>One</div>
<div>Two</div>
<div>Three</div>
</body>
</html>
this Keyword in Event Handler
• Many times it becomes very easy to make use of this keyword inside an event handler. This
keyword represents a DOM element which triggers the event.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function(){
alert($(this).text());
});
});
</script>
<style>
div{ margin:10px;padding:12px; border:2px solid #666;
width:60px;cursor:pointer}
</style>
</head>
<body>
<p>Click on any of the squares to see the result:</p>
<div>One</div>
<div>Two</div>
<div>Three</div>
</body>
</html>
• Typically, once the vent handler is established, it remains in effect for the remainder of the life of
the page. There may be need when you would like to remove event handler.
• jQuery provides the unbind() command to remove an existing event handler. The syntax is
selector.unbind(eventType, handler)
or
selector.unbind(eventType)
• Here, eventType is a string containing a JavaScript event type, such as click or submit. Refer to
the next section for a complete list of event types.
• Handler, if provided, identifies the specific listener that’s to be removed.
Method Description
blur() Triggers or binds the blur event of each matched element.
change() Triggers or binds the change event of each matched element.
click() Triggers or binds the click event of each matched element.
dblclick() Triggers or binds the dblclick event of each matched element.
focus() Triggers or binds the focus event of each matched element.
keydown() Triggers or binds the keydown event of each matched element.
keypress() Triggers or binds the keypress event of each matched element.
keyup() Triggers or binds the keyup event of each matched element.
load() Binds a function to the load event of each matched element.
mousedown() Binds a function to the mousedown event of each matched element.
mouseenter() Binds a function to the mouseenter event of each matched element.
mouseleave() Binds a function to the mouseleave event of each matched element.
mousemove() Binds a function to the mousemove event of each matched element.
mouseout() Binds a function to the mouseout event of each matched element.
mouseover() Binds a function to the mouseover event of each matched element.
mouseup() Binds a function to the mouseup event of each matched element.
resize() Binds a function to the resize event of each matched element.
scroll() Binds a function to the scroll event of each matched element.
select() Trigger or binds the select event of each matched element.
submit() Trigger or binds the submit event of each matched element.
unload() Binds a function to the unload event of each matched element.
Method Description
bind() Binds a handler to one or more events (like click) for each matched element.
Can also bind custom events.
off() This does the opposite of live, it removes a bound live events.
hover() Simulates hovering for example moving the mouse on, and off, an object.
on() Binds a handler to an event (like click) for all current – and future – mateched
element. Can also bind custom events.
one() Binds a handler to one or more events to be executed once for each matched
element.
ready() Binds a function to be executed whenever the DOM is ready to be traversed and
manipulated.
trigger() Trigger an event on every matched element.
triggerHandler() Trigges all bound event handlers on an element.
unbind() This does the opposite of bind, it removes bound events from each of the
matched elements.
Event Helper Methods
• jQuery also provides a set of event helper functions which can be used to trigger an event to
bind any event types.
• Following example which will triggers the blur event on all paragraphs.
$("p").blur();
• Binding Methods
• Following is an example which will bind a click event on all the <div>
$("div").click(function(){
//do something here
});
jQuery Effects
• jQuery provides amazing effects like show, hide, fade-in, fade-out, slide-up, slide-down, toggle
etc. jQuery methods allow us to quickly apply commonly used effect with a minimum
configuration.
• jQuery gives simple syntax to hide an element with the help of hide() method.
$(selector).hide([speed, callback]);
• Here speed, is optional parameter represents one of the three predefined speeds (“slow”,
“normal” and “fast”) or the number of milliseconds to run the animation. (e.g. 1000). By default,
speed is “normal” which is 400 milliseconds, slow 600 milliseconds and fast 200 milliseconds.
• Callback is optional parameter represents a function to be executed whenever the animation
completes; executes once for each element animated against.
• Following example where a <div> will hide itself when we click over it. We have used 1000 as
speed parameter which means it will take 1 second to apply the hide effect on the clicked
element.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function(){
$(this).hide(1000);
});
});
</script>
<style>
div{ margin:10px;padding:12px; border:2px solid #666; width:60px;
cursor:pointer}
</style>
</head>
<body>
<p>Click on any of the squares to see the result:</p>
<div>Hide Me</div>
<div>Hide Me</div>
<div>Hide Me</div>
</body>
</html>
jQuery Effect – Show Elements
• jQuery gives simple syntax to show a hidden element with the help of show() method.
$(selector).show([speed, callback]);
• Here speed, is optional parameter represents one of the three predefined speeds (“slow”,
“normal” and “fast”) or the number of milliseconds to run the animation. (e.g. 1000). By default,
speed is “normal” which is 400 milliseconds, slow 600 milliseconds and fast 200 milliseconds.
• Callback is optional parameter represents a function to be executed whenever the animation
completes; executes once for each element animated against.
• Following example where we will play with a Box with the help of two buttons. We will use these
two buttons to show and hide this Box. We have used different speeds for the two effects
hide(500) and show(1000) to show the difference in effect speed.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("#show").click(function(){
$("#box").show(1000);
});
$("#hide").click(function(){
$("#box").hide(5000);
});
});
</script>
<style>
button{cursor:pointer;}
#box{margin-bottom:5px;padding:12px;height:100px; width:125px;
background-color:#9c9cff;}
</style>
</head>
<body>
<p>Click on Show and Hide buttons to see the result:</p>
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function(){
$("#box").toggle(1000);
});
});
</script>
<style>
button{margin:3px;width:125px;cursor:pointer;}
#box{margin:3px;padding:12px; height:100px; width:100px;background-
color:#9c9cff;}
</style>
</head>
<body>
<p>Click on the Toggle Box button to see the box toggling:</p>
• jQuery gives us two methods – fadeIn() and fadeOut() to fade the DOM elements in and out
visibility.
$(selector).fadeIn([speed, callback]);
$(selector).fadeOut([speed, callback]);
• Here speed, is optional parameter represents one of the three predefined speeds (“slow”,
“normal” and “fast”) or the number of milliseconds to run the animation. (e.g. 1000). By default,
speed is “normal” which is 400 milliseconds, slow 600 milliseconds and fast 200 milliseconds.
• Callback is optional parameter represents a function to be executed whenever the animation
completes; executes once for each element animated against.
• Following example where we will play with a Box with the help of two buttons. We will use these
two buttons to show and hide this Box. We have used 1000 as speed parameter which means it
will take 1 second to apply the effect.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("#show").click(function(){
$("#box").fadeIn(1000);
});
$("#hide").click(function(){
$("#box").fadeOut(1000);
});
});
</script>
<style>
button{cursor:pointer;}
#box{margin-bottom:5px;padding:12px;height:100px; width:150px;
background-color:#9c9cff;}
</style>
</head>
<body>
<p>Click on fadeOut and fadeIn buttons to see the result:</p>
• jQuery provides fadeToggle() method to toggle the display state of elements between the
fadeIn() and fadeOut() methods. If the element is initially displayed, it will be hidden (fadeOut())
and if hidden then it will be shown (ie. fadeIn()).
$(selector).fadeToggle([speed, callback]);
• Here speed, is optional parameter represents one of the three predefined speeds (“slow”,
“normal” and “fast”) or the number of milliseconds to run the animation. (e.g. 1000). By default,
speed is “normal” which is 400 milliseconds, slow 600 milliseconds and fast 200 milliseconds.
• Callback is optional parameter represents a function to be executed whenever the animation
completes; executes once for each element animated against.
• Following example where we will play with a Square single button. When we click this button for
the first time, square box fades out (hidden), and next time when we click the button then
square box fades in (visible). We have used 1000 as speed parameter which means it will take 1
second to apply the toggle effect.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function(){
$("#box").fadeToggle(1000);
});
});
</script>
<style>
button{margin:3px;width:125px;cursor:pointer;}
#box{margin:3px;padding:12px; height:100px; width:100px;background-
color:#9c9cff;}
</style>
</head>
<body>
<p>Click on the Toggle Box button to see the box toggling:</p>
• jQuery gives us two methods – slideUp() and slideDown() to slide up and slide down the DOM
elements in and out visibility.
$(selector).slideUp([speed, callback]);
$(selector).slideDown([speed, callback]);
• Here speed, is optional parameter represents one of the three predefined speeds (“slow”,
“normal” and “fast”) or the number of milliseconds to run the animation. (e.g. 1000). By default,
speed is “normal” which is 400 milliseconds, slow 600 milliseconds and fast 200 milliseconds.
• Callback is optional parameter represents a function to be executed whenever the animation
completes; executes once for each element animated against.
• Following example where we will play with a Box with the help of two buttons. We will use these
two buttons to show and hide this Box. We have used 1000 as speed parameter which means it
will take 1 second to apply the toggle effect.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("#show").click(function(){
$("#box").slideDown(1000);
});
$("#hide").click(function(){
$("#box").slideUp(1000);
});
});
</script>
<style>
button{cursor:pointer;}
#box{margin-bottom:5px;padding:12px;height:100px; width:150px;
background-color:#9c9cff;}
</style>
</head>
<body>
<p>Click on fadeOut and fadeIn buttons to see the result:</p>
• jQuery provides slideToggle() method to toggle the display state of elements between the
slideIn() and slideOut() methods. If the element is initially displayed, it will be hidden (slideUP())
and if hidden then it will be shown (ie. slideDown()).
$(selector).slideToggle([speed, callback]);
• Here speed, is optional parameter represents one of the three predefined speeds (“slow”,
“normal” and “fast”) or the number of milliseconds to run the animation. (e.g. 1000). By default,
speed is “normal” which is 400 milliseconds, slow 600 milliseconds and fast 200 milliseconds.
• Callback is optional parameter represents a function to be executed whenever the animation
completes; executes once for each element animated against.
• Following example where we will play with a Square Box with the help of a single button. When
we click this button for the first time, square box fades out (hidden), and next time when we click
the button then square box fades in (visible). We have used 1000 as speed parameter which
means it will take 1 second to apply the toggle effect.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function(){
$("#box").slideToggle(1000);
});
});
</script>
<style>
button{margin:3px;width:125px;cursor:pointer;}
#box{margin:3px;padding:12px; height:100px; width:100px;background-
color:#9c9cff;}
</style>
</head>
<body>
<p>Click on the Toggle Box button to see the box toggling:</p>
• Consider a situation when you want to perform the following action on an HTML element:
• 1. Select a paragraph element
• 2. Change the color of the paragraph.
• 3. Apply fadeOut effect on the paragraph.
• 4. Apply fadeIn effect on the paragraph.
• Following is the jQuery program to perform the above actions.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$("p").css("color", "#fb7c7c");
$("p").fadeOut(1000);
$("p").fadeIn(1000);
});
});
</script>
<style>
button{width:100px;cursor:pointer;}
</style>
</head>
<body>
<p>Click the below button to see the result:</p>
<button>Click Me</button>
</body>
</html>
• jQuery method chaining allows us to call multiple jQuery methods using a single statement on
the same element. This gives a better performance because while using chaining, we do not
need to parse the whole page every time to find the element.
• To chain the multiple methods, we simply need to append the method to the previous method.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$("p").css("color", "#fb7c7c").fadeOut(1000).fadeIn(1000);
});
});
</script>
<style>
button{width:100px;cursor:pointer;}
</style>
</head>
<body>
<p>Click the below button to see the result:</p>
<button>Click Me</button>
</body>
</html>
Animation with Chaining
• We can take advantage of jQuery Method chaining while writing jQuery animation program.
<html>
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-
3.6.0.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$("div").animate({left: '250px'})
.animate({top: '100px'})
.animate({left: '0px'})
.animate({top: '0px'});
});
});
</script>
<style>
button {width:125px;cursor:pointer}
#box{position:relative;margin:3px;padding:10px;height:20px;
width:100px;background-color:#9c9cff;}
</style>
</head>
<body>
<p>Click on Start Animation button to see the result:</p>
• A jQuery callback function is a function that will be executed only after the current effect gets
completed. Following is a simple syntax of jQuery effect method:
$(selector).effectName(speed, callback);
• If we go in a little more detail then a jQuery callback function will be written as follows.
$(selector).effectName(speed, function(){
<!-- function body -->
});
Example without Callback Function
• Following jQuery program does not make use of callback function so here alert message is
displayed even before the hide effect is getting completed.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function(){
$(this).hide(1000);
alert("I'm hidden now");
});
});
</script>
<style>
div{ margin:10px;padding:12px; border:2px solid #666; width:60px;
cursor:pointer}
</style>
</head>
<body>
<p>Click on any of the squares to see the result:</p>
<div>Hide Me</div>
<div>Hide Me</div>
<div>Hide Me</div>
</body>
</html>
• jQuery callback functions are required due to asynchronous nature of JavaScript (jQuery) code
execution. jQuery effects may take sometime to complete, so there is a chance that the next
lines of code may get executed while the effects are still being executed.
• To handle asynchronous execution of the code, jQuery allows to pass a callback in all the effect
methods and the purpose of this callback function is to be executed only when the effect gets
completed.
• Let’s rewrite the above example again. This time we make use of a callback function which is
executed after the hide effect is completed.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-
3.6.0.js"></script>
<script>
$(document).ready(function() {
$("div").click(function(){
$(this).hide(1000, function(){
alert("I'm hidden now");
});
});
});
</script>
<style>
div{ margin:10px;padding:12px; border:2px solid #666; width:60px;
cursor:pointer}
</style>
</head>
<body>
<p>Click on any of the squares to see the result:</p>
<div>Hide Me</div>
<div>Hide Me</div>
<div>Hide Me</div>
</body>
</html>
jQuery Attributes Manipulation
• jQuery provides a number of methods to manipulate DOM in efficient way. You do not need to
write big and complex code to set or get the content of any HTML element.
• jQuery provides methods such as attr(), html(), text() and val() which act as getters and setters to
manipulate the content from HTML documents.
Note : Document Object Model (DOM) - is standard that allows us to create, change, or remove
elements from the HTML or XML documents.
• Here are some basic operations which you can perform on DOM elements with the help of jQuery
standard library methods −
o Extract the content of an element
o Change the content of an element
o Adding a child element under an existing element
o Adding a parent element above an existing element
o Adding an element before or after an existing element
o Replace an existing element with another element
o Delete an existing element
o Wrapping content with-in an element
jQuery - Get Content
• jQuery provides html() and text() methods to extract the content of the matched HTML element.
Following is the syntax of these two methods:
$(selector).html();
$(selector).text();
• The jQuery text() method returns plain text value of the content whereas html() returns the
content with HTML tags. You will need to use jQuery selectors to select the target element.
• Following example shows how to get the content with the jQuery text() and html() methods:
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("#text").click(function(){
alert($("p").text());
});
$("#html").click(function(){
alert($("p").html());
});
});
</script>
</head>
<body>
<p>The quick <b>brown fox</b> jumps over the <b>lazy dog</b></p>
• jQuery val() method is used to get the value from any form field. Following is simple syntax of
this method.
$(selector).val();
• Following is another example to show how to get the value an input field with jQuery method
val() −
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("#b1").click(function(){
alert($("#name").val());
});
$("#b2").click(function(){
alert($("#class").val());
});
});
</script>
</head>
<body>
<p>Name: <input type="text" id="name" value="Zara Ali"/></p>
<p>Class: <input type="text" id="class" value="Class 12th"/></p>
• jQuery html() and text() methods can be used to set the content of the matched HTML element.
Following is the syntax of these two methods when they are used to set the values:
$(selector).html(val, [function]);
$(selector).text(val, [function]);
• Here val is he HTML of text content to be set for the element. We can provide an optional
callback function to these methods which will be called when the value of the element will be
set.
• The jQuery text() method sets plain text value of the content whereas html() method sets the
content with HTML tags.
• Following example shows how to set the content of an element with the jQuery text() and html()
methods:
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("#text").click(function(){
$("p").text("The quick <b>brown fox</b> jumps over the <b>lazy
dog</b>");
});
$("#html").click(function(){
$("p").html("The quick <b>brown fox</b> jumps over the <b>lazy
dog</b>");
});
});
</script>
</head>
<body>
<p>Click on any of the two buttons to see the result</p>
• jQuery val() method is also used to set the value from any form field. Following is simple syntax
of this method when it is used to set the value.
$(selector).val(val);
• Here val is he value to be set for the input field. We can provide an optional callback function
which will be called when the value of the field will be set.
• Following is another example to show how to set the value an input field with jQuery method
val() −
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-
3.6.0.js"></script>
<script>
$(document).ready(function() {
$("#b1").click(function(){
$("#name").val("Zara Ali");
});
$("#b2").click(function(){
$("#class").val("Class 12th");
});
});
</script>
</head>
<body>
<p>Name: <input type="text" id="name" value=""/></p>
<p>Class: <input type="text" id="class" value=""/></p>
• The jQuery replaceWith() method can be used to replace a complete DOM element with another
HTML or DOM element. Following is the syntax of the method:
$(selector).replaceWith(val);
• Here val is what you want to have instead of original element. This could be HTML or simple text.
• Following is an example where we will replace a <p> element with an <h1> element and then
further we replace <h1> element with <h2> element.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("#b1").click(function(){
$("p").replaceWith("<h1>This is new heading</h1>");
});
$("#b2").click(function(){
$("h1").replaceWith("<h2>This is another heading</h2>");
});
});
</script>
</head>
<body>
<p>Click below button to replace me</p>
• jQuery provides various methods to add new DOM elements in the existing HTML document. You
can add these new elements at various locations (before, after any of the existing tags) based on
your requirements.
• The jQuery append() method adds the content at the end of the matched each element(s). You
can also append multiple elements in a single function call.
• Following is the syntax of the append() method:
$(selector).append(content, [content]);
• Here content parameter could be a HTML string, a DOM element, text node, array of elements and
text nodes or jQuery object to insert at the end of each element in the set of matched elements.
<div class="container">
<h2>jQuery append() Method</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
Now if we apply the append() method as follows:
<div class="container">
<h2>jQuery append() Method</h2>
<div class="inner">Hello
<p>Zara</p>
</div>
<div class="inner">Goodbye
<p>Zara</p>
</div>
</div>
Example
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$(".inner").append("<p>Zara</p>");
});
});
</script>
</head>
<body>
<div class="container">
<h2>jQuery append() Method</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
<br>
<button>Add Text</button>
</body>
</html>
jQuery appendTo() Method
• The jQuery appendTo() method performs the same task as done by appendTo(). The major
difference is in the syntax-specifically, in the placement of the content and target.
• Following is the syntax of the appendTo() method:
$(content).appendTo(selector);
• Here content parameter could be a HTML string, a DOM element, text node, array of elements
and text nodes or jQuery object to insert at the end of each element in the set of matched
elements.
Example
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$("<p>Zara</p>").appendTo(".inner");
});
});
</script>
</head>
<body>
<div class="container">
<h2>jQuery appendTo() Method</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
<br>
<button>Add Text</button>
</body>
</html>
jQuery after() Method
• The jQuery after() method adds the content after the matched each element(s). You can also insert
multiple elements in a single function call.
• Following is the syntax of the after() method:
$(selector).after(content, [content]);
• Here content parameter could be a HTML string, a DOM element, text node, array of elements and
text nodes or jQuery object to insert at the end of each element in the set of matched elements.
• Consider the following HTML content:
<div class="container">
<h2>jQuery after() Method</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
• Now if we apply the after() method as follows:
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$(".inner").after("<p>Zara</p>");
});
});
</script>
</head>
<body>
<div class="container">
<h2>jQuery after() Method</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
<br>
<button>Add Text</button>
</body>
</html>
jQuery insertAfter() Method
• The jQuery insertAfter() method adds the content after the matched each element(s). The after()
and insertAfter() methods perform the same task. The major difference is in the syntax-specifically,
in the placement of the content and target.
• Following is the syntax of the after() method:
$(content).insertAfter(selector);
• Here content parameter could be a HTML string, a DOM element, text node, array of elements and
text nodes or jQuery object to insert at the end of each element in the set of matched elements.
Example
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$("<p>Zara</p>").insertAfter(".inner");
});
});
</script>
</head>
<body>
<div class="container">
<h2>jQuery insertAfter() Method</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
<br>
<button>Add Text</button>
</body>
</html>
jQuery prepend() Method
• The jQuery prepend() method adds the content at the beginning of the matched each element(s).
You can also prepend multiple elements in a single function call.
• Following is the syntax of the append() method:
$(selector).prepend(content, [content]);
• Here content parameter could be a HTML string, a DOM element, text node, array of elements and
text nodes or jQuery object to insert at the end of each element in the set of matched elements.
• Consider the following HTML content:
<div class="container">
<h2>jQuery prepend() Method</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
• Now if we apply the prepend() method as follows:
<div class="container">
<h2>jQuery prepend() Method</h2>
<div class="inner">
<p>Zara</p>
Hello
</div>
<div class="inner">
<p>Zara</p>
Goodbye
</div>
</div>
Example
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$(".inner").prepend("<p>Zara</p>");
});
});
</script>
</head>
<body>
<div class="container">
<h2>jQuery prepend() Method</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
<br>
<button>Add Text</button>
</body>
</html>
jQuery prependTo() Method
• The jQuery prependTo() method perform the same task as done by prepend(). The major
difference is in the syntax-specifically, in the placement of the content and target.
• Following is the syntax of the prependTo() method:
$(content).prependTo(selector);
• Here content parameter could be a HTML string, a DOM element, text node, array of elements and
text nodes or jQuery object to insert at the end of each element in the set of matched elements.
Example
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$("<p>Zara</p>").prependTo(".inner");
});
});
</script>
</head>
<body>
<div class="container">
<h2>jQuery prependTo() Method</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
<br>
<button>Add Text</button>
</body>
</html>
jQuery before() Method
• The jQuery before() method adds the content before the matched each element(s). You can also
insert multiple elements in a single function call.
• Following is the syntax of the before() method:
$(selector).before(content, [content]);
• Here content parameter could be a HTML string, a DOM element, text node, array of elements and
text nodes or jQuery object to insert at the end of each element in the set of matched elements.
• Consider the following HTML content:
<div class="container">
<h2>jQuery before() Method</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
• Now if we apply the before() method as follows:
<div class="container">
<h2>jQuery before() Method</h2>
<p>Zara</p>
<div class="inner">Hello</div>
<p>Zara</p>
<div class="inner">Goodbye</div>
</div>
Example
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$(".inner").before("<p>Zara</p>");
});
});
</script>
</head>
<body>
<div class="container">
<h2>jQuery before() Method</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
<br>
<button>Add Text</button>
</body>
</html>
jQuery insertBefore() Method
• The jQuery insertBefore() method adds the content before the matched each element(s). The
before() and insertBefore() methods perform the same task. The major difference is in the syntax-
specifically, in the placement of the content and target.
• Following is the syntax of the after() method:
$(content).insertBefore(selector);
• Here content parameter could be a HTML string, a DOM element, text node, array of elements and
text nodes or jQuery object to insert at the end of each element in the set of matched elements.
Example
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$("<p>Zara</p>").insertBefore(".inner");
});
});
</script>
</head>
<body>
<div class="container">
<h2>jQuery insertBefore() Method</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
<br>
<button>Add Text</button>
</body>
</html>
• jQuery provides remove() and empty() methods to remove existing HTML elements from an HTML
document.
• The jQuery remove() method removes the selected element(s) and it's child elements from the
document.
• Following is the syntax of the remove() method:
$(selector).remove();
• You should use remove() method when you want to remove the element itself, as well as
everything inside it.
• Consider the following HTML content:
<div class="container">
<h2>jQuery remove() Method</h2>
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div>
• Now if we apply the remove() method as follows:
$( ".hello" ).remove();
• It will produce following result:
<div class="container">
<h2>jQuery remove() Method</h2>
<div class="goodbye">Goodbye</div>
</div>
• If we had any number of nested elements inside <div class="hello">, they would be removed, too.
Example
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$( ".hello" ).remove();
});
});
</script>
</head>
<body>
<div class="container">
<h2>jQuery remove() Method</h2>
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div>
<br>
<button>Remove Text</button>
</body>
</html>
Remove with Filter
• We can also include a selector as an optional parameter for the remove() method. For example,
we could rewrite the previous DOM removal code as follows:
• Let's try the following example and verify the result:
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$("div").remove(".hello");
});
});
</script>
</head>
<body>
<div class="container">
<h2>jQuery remove(selector) Method</h2>
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div>
<br>
<button>Remove Text</button>
</body>
</html>
jQuery empty() Method
• The jQuery empty() method is very similar to remove() which removes the selected element(s) and
it's child elements from the document. This method does not accept any arguments.
• Following is the syntax of the empty() method:
$(selector).empty();
• You should use empty() method when you want to remove the element itself, as well as everything
inside it.
• Consider the following HTML content:
<div class="container">
<h2>jQuery empty() Method</h2>
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div>
• Now if we apply the empty() method as follows:
$( ".hello" ).empty();
• It will produce following result:
<div class="container">
<h2>jQuery empty() Method</h2>
<div class="goodbye">Goodbye</div>
</div>
Example
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-
3.6.0.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$( ".hello" ).empty();
});
});
</script>
</head>
<body>
<div class="container">
<h2>jQuery empty() Method</h2>
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div>
<br>
<button>Remove Text</button>
</body>
</html>
jQuery - Replace Elements
• jQuery provides replaceWith() method to replace existing HTML content with a new content in a
given HTML document.
• The jQuery replaceWith() method removes the content from the DOM and inserts a new content
in it's place.
• Following is the syntax of the replaceWith() method:
$(selector).replaceWith(newContent);
• The replaceWith() method removes all data and event handlers associated with the removed
nodes.
• Consider the following HTML content:
<div class="container">
<h2>jQuery replaceWith() Method</h2>
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
<div class="hello">Hello</div>
</div>
• Now if we apply the replaceWith() method as follows:
<div class="container">
<h2>jQuery remove() Method</h2>
<h2>New Element</h2>
<div class="goodbye">Goodbye</div>
<h2>New Element</h2>
</div>
• If we had any number of nested elements inside <div class="hello">, they would be removed, too.
Example
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-
3.6.0.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$( ".hello" ).replaceWith("<h2>New Element</h2>" );
});
});
</script>
</head>
<body>
<div class="container">
<h2>jQuery replaceWith() Method</h2>
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
<div class="hello">Hello</div>
</div>
<br>
<button>Replace Element</button>
</body>
</html>
Example
<!doctype html>
<html lang="en">
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-
3.6.0.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$( "p" ).replaceWith( "<b>Brilliant</b>" );
});
});
</script>
</head>
<body>
<h2>jQuery replaceWith() Method</h2>
<p>Zara</p>
<p>Nuha</p>
<p>Ayan</p>
<button>Replace Element</button>
</body>
</html>
• jQuery provides css() method to manipulate CSS properties of the matched elements.
• JQuery css() method does not modify the content of the jQuery object but they are used to get
and set CSS properties on DOM elements.
$(selector).css(propertyName);
• jQuery understands and returns the correct value for both css( "background-color" ) and css(
"backgroundColor" ).
Example
• Let's try the following example and verify the result. This should return the background color of
the first matched <div>.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
alert("Background color = " + $("div").css("background-color"));
});
});
</script>
<style>
button{margin:10px;width:150px;cursor:pointer}
div{ margin:10px;padding:12px; width:125px;}
</style>
</head>
<body>
<p>Click the below button to see the result:</p>
<div style="background-color:#9c9cff;">Blue</div>
<div style="background-color:#93ff93;">Green</div>
• jQuery css() method can be used to set the value of one or more CSS properties associated with
the matched HTML element. Following is the syntax of the css() method:
$(selector).css(propertyName, value);
• Here both the parameters are required, propertyName represents a CSS property name where as
value represents a valid value of the property.
Example
• Let's try the following example and verify the result. Here we will take the color of the first matched
<div> and will change the text color of all <p> using the div background-color.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
var color = $("div").css("background-color");
$("p").css("color", color);
});
});
</script>
<style>
button{margin:10px;width:150px;cursor:pointer}
div{ margin:10px;padding:12px; width:125px;}
</style>
</head>
<body>
<p>Click the below button to see the result:</p>
<div style="background-color:#9c9cff;">Blue</div>
<div style="background-color:#93ff93;">Green</div>
• You can apply multiple CSS properties on the matched elements using a single jQuery method
css(). You can apply as many properties as you like in a single call.
• Following is the syntax of the css() method to set multiple CSS properties:
$(selector).css({propertyName1:value1, propertyName2:value2,...});
Example
• Let's try the following example and verify the result. Here we will set background color of all the
<div> to "#fb7c7c;" and font-size to 25px.
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="js/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$("div").css({"background-color":"#fb7c7c", "font-size":
"25px"});
});
});
</script>
<style>
button{margin:10px;width:150px;cursor:pointer}
div{ margin:10px;padding:12px; width:125px;}
</style>
</head>
<body>
<p>Click the below button to see the result:</p>
<div style="background-color:#9c9cff;">Blue</div>
<div style="background-color:#93ff93;">Green</div>