JavaScript
JavaScript
What is JavaScript?
Although, JavaScript has no connectivity with Java programming language. The name was
suggested and provided in the times when Java was gaining popularity in the market. In addition
to web browsers, databases such as CouchDB and MongoDB uses JavaScript as their scripting
and query language.
Features of JavaScript:
1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is
a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast (depending
on the operation).
6. It is a case-sensitive language.
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog
box and prompt dialog box),
o Displaying clocks etc.
Where to insert
Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.
External file:
External scripts are practical when the same code is used in many different web pages.
To use an external script, put the name of the script file in the src (source) attribute of
a <script> tag:
<html>
<head>
<script src=”abc.js”>
</script>
</head>
</html>
abc.js
JavaScript Output
Using innerHTML
The id attribute defines the HTML element. The innerHTML property defines the HTML
content:
<body>
<script>
function changeTitle() {
</script>
</body>
Using document.write()
<body>
<script>
document.write("hello");
</script>
</body>
Example2;
<body>
</body>
Using window.alert()
<body>
<script>
window.alert(“hello”); //alert(“hello”);
</script>
</body>
Using console.log()
For debugging purposes, you can call the console.log() method in the browser to display
data.
JavaScript Print
The only exception is that you can call the window.print() method in the browser to print
the content of the current window.
<body>
</body>
Window prompt()
The prompt() method displays a dialog box that prompts the user for input.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed.
<body>
<script>
var z=x+y;
document.write(z);
</script>
</body>
JavaScript Example:
<html>
<body>
<h2>Welcome to JavaScript</h2>
<script>
</script>
</body>
</html>
JavaScript Variable
A JavaScript variable is simply a name of storage location. There are two types of variables in
JavaScript: local variable and global variable. There are some rules while declaring a JavaScript
variable (also known as identifiers).
Identifiers can be short names (like x and y) or more descriptive names (age, sum, total Volume).
The general rules for constructing names for variables (unique identifiers) are:
var carName;
1. var x = 10;
2. var _value="sonoo";
1. var 123=30;
2. var *aa=320;
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
Output:30
A JavaScript local variable is declared inside block or function. It is accessible within the
function or block only.
1. <script>
2. function abc(){
3. var x=10;//local variable
4. }
5. </script>
Or,
1. <script>
2. If(10<13){
3. var y=20;//JavaScript local variable
4. }
5. </script>
A JavaScript global variable is accessible from any function. A variable i.e. declared outside
the function or declared with window object is known as global variable.
Example:
<html>
<body>
<script>
function a(){
document.writeln(data);
function b(){
document.writeln(data);
b();
</script>
</body>
</html>
JavaScript Arrays
What is an Array?
An array is a special variable, which can hold more than one value at a time.
i) Creating an Array:
Using an array literal is the easiest way to create a JavaScript Array.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
</body></html>
Output:
JavaScript Arrays
Saab,Volvo,BMW
Spaces and line breaks are not important. A declaration can span multiple lines:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
var cars = [
"Saab",
"Volvo",
"BMW"
];
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>
Saab,Volvo,BMW
Example:
<html>
<body>
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>
Output:
Arun
Varun
John
To create instance of array by passing arguments in constructor so that we don't have to provide
value explicitly.
<html>
<body>
<script>
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
</script>
</body>
</html>
Output: Jai
Vijay
Smith
concat() It returns a new array object that contains two or more merged arrays.
copywithin() It copies the part of the given array with its own elements and returns the modified array.
entries() It creates an iterator object and a loop that iterates over each key/value pair.
every() It determines whether all the elements of an array are satisfying the provided function
conditions.
flat() It creates a new array carrying sub-array elements concatenated recursively till the specified
depth.
flatMap() It maps all array elements via mapping function, then flattens the result into a new array.
from() It creates a new array carrying the exact copy of another array element.
filter() It returns the new array containing the elements that pass the provided function conditions.
find() It returns the value of the first element in the given array that satisfies the specified condition.
findIndex() It returns the index value of the first element in the given array that satisfies the specified
condition.
forEach() It invokes the provided function once for each element of an array.
includes() It checks whether the given array contains the specified element.
indexOf() It searches the specified element in the given array and returns the index of the first match.
keys() It creates an iterator object that contains only the keys of the array, then loops through these
keys.
lastIndexOf() It searches the specified element in the given array and returns the index of the last match.
map() It calls the specified function for every array element and returns the new array
of() It creates a new array from a variable number of arguments, holding any type of argument.
reduce(function, It executes a provided function for each value from left to right and reduces the array to a single
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For example:
car, pen, bike, chair, glass, keyboard, monitor etc.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
1) JavaScript Object by object literal: syntax of creating object using object literal is
object={property1:value1,property2:value2.....propertyN:valueN}
property and value is separated by : (colon).
Example:
<html>
<body>
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>
Output: 102 Shyam Kumar 40000
Object Properties:
1. age 50
2.firstName John
Accessing Object Properties: You can access object properties in two ways:
objectName.propertyName / objectName["propertyName"]
example of
<html>
<body>
<script>
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
</script>
</body>
</html>
Output: 101 Ravi Malik 50000
Here, you need to create function with arguments. Each argument value can be assigned in the
current object by using this keyword.The this keyword refers to the current object.
Example:
<html>
<body>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
</script>
</body>
</html>
<html>
<body>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
e.changeSalary(45000);
</script>
</body>
</html>
Output: 103 Sonoo Jaiswal 30000
103 Sonoo Jaiswal 45000
JavaScript Objects:
Document
Arrays
Math objects
String objects
Date Objects
DOM:When a web page is loaded, the browser creates a Document Object Model of the
page.
If you want to access any element in an HTML page, you always start with accessing the
document object.
The easiest way to find an HTML element in the DOM, is by using the element id.
Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
</script>
</body>
</html>
If the element is found, the method will return the element as an object (in myElement).
var x = document.getElementsByTagName("p");
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
</script>
</body>
</html>
If you want to find all HTML elements with the same class name, use
getElementsByClassName().
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const x = document.getElementsByClassName("intro");
document.getElementById("demo").innerHTML =
</script>
</body>
</html>
DOM manipulation
Table of Content
There are multiple methods available in DOM to select the HTML elements and
manipulate them as listed below:
querySelector() method: A query selector is a method used in JavaScript to select
and manipulate elements in the Document Object Model (DOM). It allows you to
retrieve elements from an HTML document using CSS selectors.
<!DOCTYPE html>
<html>
<head>
<title>
GeeksForGeeks
</title>
</head>
<div id="target">
<h1>Hello Geeks</h1>
<h2 class="example">
</h2>
<p>
</p>
<p>
</p>
id="userName">
</div>
<script>
const queryS =
document.querySelector(".example");
const gebi =
document.getElementById("target");
const gebcn =
document.getElementsByClassName('example');
const gebtn =
document.getElementsByTagName('p');
const gebn =
document.getElementsByName('username');
const querySAll =
document.querySelectorAll("p");
console.log(queryS);
console.log(gebi);
console.log(gebcn);
console.log(gebn);
console.log(gebtn);
console.log(querySAll);
</script>
</body>
The below DOM properties can be used to change the HTML and the text content of
the HTML elements.
textContent: The textContent property is used to set and get the text content and it's
descendants.
innerHTML: The innerHTML property is used to get and set the text
and HTML inside an HTML element.
innerText: The innerText property represents the rendered text content of a node
and its descendants. It is aware of the elements which will be rendered and ignores
the hidden elements.
<!DOCTYPE html>
<html>
<head>
<title>
</title>
You can also create dynamic HTML elements using the below DOM methods.
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<h2>Hello 2</h2>
<h3>Hello 3</h3>
<script>
const para =
document.createElement("p");
para.textContent =
const para1 =
document.createTextNode("p");
para1.textContent =
document.body.appendChild(para);
document.body.appendChild(para1);
</script>
</body>
</html>
cssText: CSS can be directly manipulated using the cssText property of the style
object to set multiple inline styles at a time. It is similar to how we add inline CSS to
an element.
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<style>
.classList {
color: white;
background-color: black;
text-align: center
</style>
</head>
<body>
<h1>Hello 1</h1>
<h2>Hello 2</h2>
<h3>Hello 3</h3>
<script>
const tcontentexample =
document.querySelector("h1");
const innerhtmlexample =
document.querySelector("h2");
const innertextexample =
document.querySelector("h3");
tcontentexample.style.
color = "white";
tcontentexample.style.
backgroundColor = "black";
tcontentexample.style.
textAlign = "center";
innerhtmlexample.style.cssText =
`color: white;
background-color: black;
text-align:center`;
innertextexample.classList.add("classList");
</script>
</body>
</html>
1 Object.assign() This method is used to copy enumerable and own properties from a
source object to a target object
2 Object.create() This method is used to create a new object with the specified prototype
object and properties.
5 Object.entries() This method returns an array with arrays of the key, value pairs.
7 Object.getOwnPropertyDescriptor() This method returns a property descriptor for the specified property of
the specified object.
8 Object.getOwnPropertyDescriptors() This method returns all own property descriptors of a given object.
9 Object.getOwnPropertyNames() This method returns an array of all properties (enumerable or not) found.
10 Object.getOwnPropertySymbols() This method returns an array of all own symbol key properties.
16 Object.keys() This method returns an array of a given object's own property names.
18 Object.seal() This method prevents new properties from being added and marks all
existing properties as non-configurable.
19 Object.setPrototypeOf() This method sets the prototype of a specified object to another object.
The math object provides the properties and methods for mathematical constants and
functions. Unlike the other global objects, Math is not a constructor. All properties and
methods of Math are static and can be called by using Math as an object without creating it.
varsine_val = Math.sin(30)
Math Properties
Property Description
3.14159.
approximately 0.707.
Math Methods
Method Description
pow() Returns base to the exponent power, that is, base exponent.
Eg: document.writeln(math.pi);
String Methods
Method Description
concat() Combines the text of two strings and returns the combined string.
indexOf() Returns the index of the first occurrence of the String object of
or -1 if not found.
lastIndexOf() Returns the index within the calling String object of the last
occurrence of the specified valu match() Used to match a regular expression against a string.
string.
toUpperCase() Returns the calling string value converted to uppercase.e, or -1 if not found.
The Date object is a data type built into the JavaScript language. Once a Date object is created, a number
of methods are available to operate onit.
new Date( ) - This constructor creates a Date object set to the current date and time.
new Date(milliseconds)- When one numeric argument is passed, it is taken as the internal numeric
representation of the date in milliseconds, as returned bythe getTime( ) method
Date Methods
Method Description
Date() Returns today's date and time
getDate() Returns the day of the month for the specified date
accordingto local time.
getDay() Returns the day of the week for the specified date according
tolocal time.
getFullYear() Returns the year of the specified date according to local time.
getHours() Returns the hour in the specified date according to local time.
getMilliseconds() Returns the milliseconds in the specified date according to
local time.
getMinutes() Returns the minutes in the specified date according to local
time.
getMonth() Returns the month in the specified date according to local
time
setDate() Sets the day of the month for a specified date according to
local time.
setFullYear() Sets the full year for a specified date according to local time.
setHours() Sets the hours for a specified date according to local time.
time.
setMinutes() Sets the minutes for a specified date according to local time.
setMonth() Sets the month for a specified date according to local time.
setSeconds() Sets the seconds for a specified date according to local time.
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in
loops. It makes the code compact. It is mostly used in array.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
The JavaScript for loop iterates the elements for the fixed number of times. It should be
used if number of iteration is known.
Example:
<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
</body>
</html>
Output:
1
2
3
4
5
2) JavaScript while loop: The JavaScript while loop iterates the elements for the infinite
number of times. It should be used if number of iteration is not known.
Example:
<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=15)
document.write(i + "<br/>");
i++;
</script>
</body>
</html>
output:
11
12
13
14
15
The JavaScript do while loop iterates the elements for the infinite number of times like while
loop. But, code is executed at least once whether condition is true or false.
syntax: do{
code to be executed
}while (condition);
Example:
<!DOCTYPE html>
<html>
<body>
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
</body>
</html>
Output:
21
22
23
24
25
Conditionals
Conditional statements are used to perform different actions based on different conditions.
Output:
<html>
<body>
<script>
var a=20;
if(a>10){
</script>
</body>
</html>
Syntax:
1. if(expression){
2. //content to be evaluated if condition is true
3. }
4. else{
5. //content to be evaluated if condition is false
6. }
Example:
<html>
<body>
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
</body>
</html>
output: a is even number
Syntax:
1. if(expression1){
2. //content to be evaluated if expression1 is true
3. }
4. else if(expression2){
5. //content to be evaluated if expression2 is true
6. }
7. else if(expression3){
8. //content to be evaluated if expression3 is true
9. }
10. else{
11. //content to be evaluated if no expression is true
12. }
Example:
<html>
<body>
<script>
var a=20;
if(a==10){
else if(a==15){
else if(a==20){
else{
</script>
</body>
</html>
Output: a is equal to 20
Use the switch statement to select one of many code blocks to be executed.
Syntax:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Example:
<!DOCTYPE html>
<html>
<body>
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
document.write(result);
</script>
</body>
</html>
output: B Grade
When JavaScript reaches a break keyword, it breaks out of the switch block.
It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.
The switch statement is fall-through i.e. all the cases will be evaluated if you don't use break
statement.
Example:
<!DOCTYPE html>
<html>
<body>
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result+=" A Grade";
case 'B':
result+=" B Grade";
case 'C':
result+=" C Grade";
default:
result+=" No Grade";
document.write(result);
</script>
</body>
</html>
output: undefined B Grade C Grade No Grade
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many
times to reuse the code.
Example: <html>
<body>
<script>
function msg(){
alert("hello! this is message");
</script>
</body>
</html>
output:
call function
Function Invocation:
The code inside the function will execute when "something" invokes (calls) the function:
Function with Return Value:We can call function that returns a value and use it in our
program.
<html>
<body>
<script>
function getInfo(){
</script>
<script>
document.write(getInfo());
</script>
</body>
</html>
Syntax:
Parameter
Method Description
apply() It is used to call a function contains this value and a single array of arguments.
call() It is used to call a function contains this value and an argument list.
Example:
<!DOCTYPE html>
<html>
<body>
<script>
document.writeln(add(2,5));
</script>
</body>
</html>
output:7
Predefined functions:
Isfinite()
isNan()
ParseInt()
parseFloat()
Eval()
JavaScript Events
The change in the state of an object is known as an Event. In html, there are various events
which represents that some activity is performed by the user or by the browser.
When javascript code is included in HTML, js react over these events and allow the execution.
This process of reacting over the events is called Event Handling. Thus, js handles the HTML
events via Event Handlers.
For example, when a user clicks over the browser, add js code, which will execute the task to be
performed on the event.
Mouse events:
Mouseover Onmouseover When the cursor of the mouse comes over the element
Mouseout Onmouseout When the cursor of the mouse leaves an element
Mousedown Onmousedown When the mouse button is pressed over the element
Mouseup Onmouseup When the mouse button is released over the element
Keyboard events:
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
Form events:
Change Onchange When the user modifies or changes the value of a form elem
Window/Document events:
Load Onload When the browser finishes the loading of the page
Unload onunload When the visitor leaves the current webpage, the browser unlo
Resize Onresize When the visitor resizes the window of the browser
Click Event:
<html>
<body>
function clickevent()
document.write("This is JavaTpoint");
</script>
<form>
</form>
</body>
</html>
Keydown Event:
<html>
<body>
<script>
function keydownevent()
document.getElementById("input1");
alert("Pressed a key");
</script>
</body>
</html>
Load event:
<html>
<head>Javascript Events</head>
</br>
<script>
</script></body></html>
Form Validating
It is important to validate the form submitted by the user because it can have inappropriate
values. So, validation is must to authenticate user.
JavaScript provides facility to validate the form on the client-side so data processing will be
faster than server-side validation. Most of the web developers prefer JavaScript form validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers and more
fields.
Example: In this example, we are going to validate the name and password. The name can’t be
empty and password can’t be less than 6 characters long.
Here, we are validating the form on form submit. The user will not be forwarded to the next page
until given values are correct.
<html>
<body>
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
return false;
}else if(password.length<6){
return false;
}
}
</script>
<body>
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;
if(firstpassword==secondpassword){
return true;
}
else{
return false;
</script>
</head>
<body>
<input type="submit">
</form>
</body>
</html>
Let's validate the textfield for numeric value only. Here, we are using isNaN() function.
<!DOCTYPE html>
<html>
<head>
<script>
function validate(){
var num=document.myform.num.value;
if (isNaN(num)){
return false;
}else{
return true;
</script>
</head>
<body>
</form>
</body>
</html>
JavaScript validation with image: Let’s see an interactive JavaScript form validation example
that displays correct and incorrect image if input is correct or incorrect.
<html>
<body>
<script type="text/javascript">
function validate(){
var name=document.f1.name.value;
var passwordlength=document.f1.password.value.length;
var status=false;
if(name==""){
document.getElementById("namelocation").innerHTML=
status=false;
}else{
document.getElementById("namelocation").innerHTML=" <img
src='http://www.javatpoint.com/javascriptpages/images/checked.gif'/>";
status=true;
if(passwordlength<6){
document.getElementById("passwordlocation").innerHTML=
status=false;
}else{
document.getElementById("passwordlocation").innerHTML=" <img
src='http://www.javatpoint.com/javascriptpages/images/checked.gif'/>";
}
return status;
</script>
<table>
</table>
</form>
</body>
</html>
AJAX
A browser built-in XMLHttpRequest object (to request data from a web server)
JavaScript and HTML DOM (to display or use the data).
AJAX allows web pages to be updated asynchronously by exchanging data with a web
server behind the scenes. This means that it is possible to update parts of a web page,
without reloading the whole page.
The XMLHttpRequest object can be used to exchange data with a web server behind the scenes.
This means that it is possible to update parts of a web page, without reloading the whole page.
All modern browsers (Chrome, Firefox, IE7+, Edge, Safari, Opera) have a built-
in XMLHttpRequest object.
GET or POST?
GET is simpler and faster than POST, and can be used in most cases.
Method Description
The status property and the statusText property holds the status of the XMLHttpRequest object.
syntax
document.getElementById("demo").innerHTML = this.responseText;
};
Property Description
Onreadystatechange Defines a function to be called when the readyState property changes
Property Description
Example
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h2>Let AJAX change this text</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "12.txt",true);
xhttp.send();
}
</script>
</body>
</html>
AJAX Database: AJAX can be used for interactive communication with a database.
How a web page can fetch information from a database with AJAX:
<!DOCTYPE html>
<html>
<head>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
xmlhttp.onreadystatechange=function() {
document.getElementById("txtHint").innerHTML=this.responseText;
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
</script>
</head>
<body>
<form>
</form>
<br>
</body>
</html>
Php file
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
table, td, th {
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','test');
if (!$con) {
mysqli_select_db($con,"user");
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "</tr>";
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
AJAX XML: AJAX can be used for interactive communication with an XML file.
<!DOCTYPE html>
<html>
<style>
table,th,td {
border-collapse: collapse;
}
th,td {
padding: 5px;
</style>
<body>
<br><br>
<table id="demo"></table>
<script>
function loadDoc() {
xhttp.onreadystatechange = function() {
myFunction(this);
};
xhttp.send();
function myFunction(xml) {
var i;
var x = xmlDoc.getElementsByTagName("CD");
table += "<tr><td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"</td></tr>";
document.getElementById("demo").innerHTML = table;
</script>
</body>
</html>
jQuery
What is jQuery?
Sometimes, a question can arise that what is the need of jQuery or what difference it makes on
bringing jQuery instead of AJAX/ JavaScript? If jQuery is the replacement of AJAX and
JavaScript? For all these questions, you can state the following answers.
So, you can say that out of the lot of JavaScript frameworks, jQuery is the most popular and the
most extendable. Many of the biggest companies on the web use jQuery.
o Microsoft
o Google
o IBM
o Netflix
There are several ways to start using jQuery on your web site. You can:
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
Popular CDNs
Downloading jQuery:
Production version - this is for your live website because it has been minified and
compressed
Development version - this is for testing and development (uncompressed and readable
code)
The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag
(notice that the <script> tag should be inside the <head> section):
<head>
<script src="jquery-3.5.1.min.js"></script>
</head>
jQuery Syntax:
The jQuery syntax is tailor-made for selecting HTML elements and performing some action on
the element(s).
Examples:
OR
$(function(){
});
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.
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
<html>
<head>
</script>
$(document).ready(function() {
$("p").css("background-color", "cyan");
});
</script>
</head>
<body>
</body>
</html>
jQuery Selectors
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 jQuery element selector selects elements based on the element name.
$("p")
Example:
<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
</body>
</html>
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:
When a user clicks on a button, the element with id="test" will be hidden:
<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<button>Click me</button>
</body>
</html>
To find elements with a specific class, write a period character, followed by the name of the
class:
$(".test")
Example
When a user clicks on a button, the elements with class="test" will be hidden:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js "></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
</script>
</head>
<body>
<button>Click me</button>
</body>
</html>
Syntax Description
$("ul li:first") Selects the first <li> element of the first <ul>
Mouse Events
i) click():
The function is executed when the user clicks on the HTML element.
The following example says: When a click event fires on a <p> element; hide the
current <p> element:
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
</head>
<body>
<p>Click me away!</p>
<p>Click me too!</p>
</body></html>
ii) dblclick():
The function is executed when the user double-clicks on the HTML element:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("p").dblclick(function(){
$(this).hide();
});
});
</script>
</head>
<body>
<p>Click me away!</p>
<p>Click me too!</p>
</body>
</html>
iii) mouseenter():
The function is executed when the mouse pointer enters the HTML element:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("#p1").mouseenter(function(){
});
});
</script>
</head>
<body>
</body>
</html>
iv) mouseleave():
The function is executed when the mouse pointer leaves the HTML element:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("#p1").mouseleave(function(){
});
});
</script>
</head>
<body>
</body>
</html>
v) mousedown():
The function is executed, when the left, middle or right mouse button is pressed down, while the
mouse is over the HTML element:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("#p1").mousedown(function(){
});
});
</script>
</head>
<body>
</body>
</html>
vi) mouseup():
The function is executed, when the left, middle or right mouse button is released, while the
mouse is over the HTML element:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("#p1").mouseup(function(){
});
});
</script>
</head>
<body>
</body>
</html>
Form Events
The submit() method triggers the submit event, or attaches a function to run when a submit event
occurs.
Syntax:
<form action="">
First name: <input type="text" name="FirstName" value="Mickey"><br>
Last name: <input type="text" name="LastName" value="Mouse"><br>
</form>
</body>
</html>
ii) change():The change event occurs when the value of an element has been changed (only
works on <input>, <textarea> and <select> elements).
The change() method triggers the change event, or attaches a function to run when a change
event occurs.
Syntax:
$(selector).change()
$(selector).change(function)
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("input").change();
});
});
</script>
</head>
<body>
<p>Click the button to trigger the change event (even if the element has not been changed).</p>
</body>
</html>
iii)focus():The focus event occurs when an element gets focus (when selected by a mouse click
or by "tab-navigating" to it).
The focus() method triggers the focus event, or attaches a function to run when a focus event
occurs.
Syntax:
$(selector).focus()
$(selector).focus(function)
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("input").focus();
});
$("#btn2").click(function(){
$("input").blur();
});
});
</script>
</head>
<body>
<br><br>
<p style="color:red"></p>
</body>
</html>
iv) blur():
The blur() method attaches an event handler function to an HTML form field.
The function is executed when the form field loses focus:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("input").focus(function(){
$(this).css("background-color", "yellow");
});
$("input").blur(function(){
$(this).css("background-color", "green");
});
});
</script>
</head>
<body>
</body>
</html>
DOM Manipulation
jQuery provides various methods to add, edit or delete DOM element(s) in the HTML page.
The following table lists some important methods to add/remove new DOM elements.
Method Description
append() Inserts content at the end of the selected elements
before() Inserts content before the selected elements.
after() Inserts content after the selected elements.
prepend() Inserts content at the beginning of the selected elements
remove() Removes element(s) from DOM which is specified by selector.
replaceAll() Replace target element(s) with specified element.
wrap() Wrap an HTML structure around each element which is specified by selector.
The following figure shows how the DOM manipulation methods add new elements.
The jQuery after() method inserts content (new or existing DOM elements) after target
element(s) which is specified by a selector.
Syntax:
$('selector expression').after('content');
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js">
</script>
<script>
$(document).ready(function () {
});
</script>
<style>
div{
border: 1px solid;
background-color:red;
margin: 2px 0 2px 0;
}
</style>
</head>
<body>
<h1>Demo: jQuery after() method </h1>
<div id="div1">division1
</div>
<div id="div2">division2
</div>
</body>
</html>
The jQuery before() method inserts content (new or existing DOM elements) before target
element(s) which is specified by a selector.
Syntax:
$('selector expression').before('content');
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js">
</script>
<script>
$(document).ready(function () {
});
</script>
<style>
div{
background-color:red;
</style>
</head>
<body>
<div id="div1">div 1
</div>
<div id="div2">div 2
</div>
</body>
</html>
The jQuery append() method inserts content to the end of target element(s) which is specified
by a selector.
Syntax:
$('selector expression').append('content');
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js">
</script>
<script>
$(document).ready(function () {
$('p').append('World!');
});
</script>
</head>
<body>
<p>Hello </p>
</body>
</html>
The jQuery prepend() method inserts content at the beginning of an element(s) specified by a
selector.
Syntax:
$('selector expression').prepend('content');
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js">
</script>
<script>
$(document).ready(function ()
});
</script>
</head>
<body>
<div>
<label>This is div.</label>
</div>
</body>
</html>
Syntax:
$('selector expression').remove();
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js">
</script>
<script>
$(document).ready(function () {
$('label').remove();
});
</script>
</head>
<body>
<div>This is div.
<label>This is label.</label>
</div>
</body></html>
<!DOCTYPE html>
<html>
<head>
<script src=" https://code.jquery.com/jquery-3.7.1.js "></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").empty();
});
});
</script>
</head>
<body>
</div>
<br>
</body>
</html>
The jQuery replaceAll() method replaces all target elements with specified element(s).
Syntax:
$('content string').replaceAll('selector expression');
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js">
</script>
<script>
$(document).ready(function () {
$('<span>This is span</span>').replaceAll('p');
});
</script>
</head>
<body>
<div>
<p>This is paragraph.</p>
</div>
</body>
</html>
The jQuery wrap() method wrap each target element with specified content element.
Syntax:
$('selector expression').wrap('content string');
Example:
<!DOCTYPE html>
<html>
<head>
<script src=" https://code.jquery.com/jquery-3.7.1.js "></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").wrap("<div></div>");
});
});
</script>
<style>
div{background-color: yellow;}
</style>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
});
$("#btn2").click(function(){
});
});
</script>
</head>
<body>
<p id="test">This is some <b>bold</b> text in a paragraph.</p>
</body>
</html>
The following example demonstrates how to get the value of an input field with
the jQuery val() method:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
});
});
</script>
</head>
<body>
<p>Name: <input type="text" id="test" value="Mickey Mouse"></p>
<button>Show Value</button>
</body>
</html>
The following example demonstrates how to get the value of the href attribute
in a link:
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></
script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert($("#abc").attr("href"));
});
});
</script>
</head>
<body>
</body>
</html>
i) jQuery hide() and show():With jQuery, you can hide and show HTML elements with
the hide() and show() methods.
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
});
</script>
</head>
<body>
<p>If you click on the "Hide" button, I will disappear.</p>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>
ii) jQuery Fading Methods:
fadeIn()
fadeOut()
fadeToggle()
fadeTo()
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
});
</script>
</head>
<body>
</body>
</html>
Syntax:
$(selector).fadeOut(speed,callback);
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:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeOut();
$("#div2").fadeOut("slow");
$("#div3").fadeOut(3000);
});
});
</script>
</head>
<body>
</body>
</html>
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);
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:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeToggle();
$("#div2").fadeToggle("slow");
$("#div3").fadeToggle(3000);
});
});
</script>
</head>
<body>
<p>Demonstrate fadeToggle() with different speed parameters.</p>
<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>
</body>
</html>
d) jQuery fadeTo() Method:
The jQuery fadeTo() method allows fading to a given opacity (value between 0 and 1).
Syntax:
$(selector).fadeTo(speed,opacity,callback);
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:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeTo("slow", 0.15);
$("#div2").fadeTo("slow", 0.4);
$("#div3").fadeTo("slow", 0.7);
});
});
</script>
</head>
<body>
</body>
</html>
slideDown()
slideUp()
slideToggle()
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<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>
</head>
<body>
<div id="flip">Click to slide down panel</div>
<div id="panel">Hello world!</div>
</body>
</html>
b) jQuery slideUp() Method:
Syntax:
$(selector).slideUp(speed,callback);
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.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideUp("slow");
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
#panel {
padding: 50px;
</style>
</head>
<body>
</body>
</html>
The 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.
$(selector).slideToggle(speed,callback);
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.
Syntax:
$(selector).animate({params},speed,callback);
The optional callback parameter is a function to be executed after the animation completes.
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({left: '250px'});
});
});
</script>
</head>
<body>
<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>
</body>
</html>
a) jQuery animate() - Manipulate Multiple Properties: multiple properties can be
animated at the same time.
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',
height: '150px',
width: '150px'
});
});
});
</script>
</head>
<body>
<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>
</body>
</html>
b) 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:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left: '250px',
height: '+=150px',
width: '+=150px'
});
});
});
</script>
</head>
<body>
<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>
</body>
</html>
c) jQuery animate() - Using Pre-defined Values:
You can even specify a property's animation value as "show", "hide", or "toggle":
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
height: 'toggle'
});
});
});
</script>
</head>
<body>
<p>Click the button multiple times to toggle the animation.</p>
<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>
</body>
</html>
d) jQuery animate() - Uses Queue Functionality:
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.
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
});
});
</script>
</head>
<body>
<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>
</body>
</html>
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);
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:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<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-radius: 3px;
#panel {
padding: 50px;
display: none;
</style>
</head>
<body>
</body>
</html>
Traversing
Traversing in jQuery allows you to navigate through the DOM (Document Object Model) to find,
filter, or manipulate elements relative to a selected element.
jQuery traversing, which means "move through", are used to "find" (or select) HTML elements based on
their relation to other elements. Start with one selection and move through that selection until you reach
the elements you desire.
The image below illustrates an HTML page as a tree (DOM tree). With jQuery traversing, you can easily
move up (ancestors), down (descendants) and sideways (siblings) in the tree, starting from the selected
(current) element. This movement is called traversing - or moving through - the DOM tree.
The <div> element is the parent of <ul>, and an ancestor of everything inside of it
The <ul> element is the parent of both <li> elements, and a child of <div>
The left <li> element is the parent of <span>, child of <ul> and a descendant of <div>
The <span> element is a child of the left <li> and a descendant of <ul> and <div>
The two <li> elements are siblings (they share the same parent)
The right <li> element is the parent of <b>, child of <ul> and a descendant of <div>
The <b> element is a child of the right <li> and a descendant of <ul> and <div>
The next chapters will show us how to travel up, down and sideways in the DOM tree.
Three useful jQuery methods for traversing up the DOM tree are:
parent()
parents()
parentsUntil()
The parent() method returns the direct parent element of the selected element.
This method only traverse a single level up the DOM tree.
<!DOCTYPE html>
<html>
<head>
<style>
.ancestors * {
display: block;
color: lightgrey;
padding: 5px;
margin: 15px;
</style>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
});
</script>
</head>
<body>
<div class="ancestors">
<ul>ul (grandparent)
<span>span</span>
</li>
</ul>
</div>
<span>span</span>
</p>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>
.ancestors * {
display: block;
color: lightgrey;
padding: 5px;
margin: 15px;
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
});
</script>
</head>
<body class="ancestors">body (great-great-grandparent)
<ul>ul (grandparent)
<span>span</span>
</li>
</ul>
</div>
</body>
<!-- The outer red border, before the body element, is the html element (also an ancestor) -->
</html>
parentsUntil() Method
The parentsUntil() method returns all ancestor elements between two given arguments.
The following example returns all ancestor elements between a <span> and a <div> element
<!DOCTYPE html>
<html>
<head>
<style>
.ancestors * {
display: block;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
});
</script>
</head>
<ul>ul (grandparent)
<span>span</span>
</li>
</ul>
</div>
</body>
</html>
With jQuery you can traverse down the DOM tree to find descendants of an element.
children()
find()
The children() method returns all direct children of the selected element.
This method only traverses a single level down the DOM tree.
The following example returns all elements that are direct children of each <div> elements:
<!DOCTYPE html>
<html>
<head>
<style>
.descendants * {
display: block;
color: lightgrey;
padding: 5px;
margin: 15px;
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
});
</script>
</head>
<body>
<div class="descendants" style="width:500px;">div (current element)
<p>p (child)
<span>span (grandchild)</span>
</p>
<p>p (child)
<span>span (grandchild)</span>
</p>
</div>
</body>
</html>
The find() method returns descendant elements of the selected element, all the way down to the last
descendant.
The following example returns all <span> elements that are descendants of <div>:
<!DOCTYPE html>
<html>
<head>
<style>
.descendants * {
display: block;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
});
</script>
</head>
<body>
<p>p (child)
<span>span (grandchild)</span>
</p>
<p>p (child)
<span>span (grandchild)</span>
</p>
</div>
</body>
</html>
With jQuery you can traverse sideways in the DOM tree to find siblings of an element.
There are many useful jQuery methods for traversing sideways in the DOM tree:
siblings()
next()
nextAll()
nextUntil()
prev()
prevAll()
prevUntil()
The siblings() method returns all sibling elements of the selected element.
The following example returns all sibling elements of <h2>:
<!DOCTYPE html>
<html>
<head>
<style>
.siblings * {
display: block;
color: lightgrey;
padding: 5px;
margin: 15px;
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("h2").siblings().css({"color": "red", "border": "2px solid red"});
});
</script>
</head>
<body class="siblings">
<div>div (parent)
<p>p</p>
<span>span</span>
<h2>h2</h2>
<h3>h3</h3>
<p>p</p>
</div>
</body>
</html>
Filtering
Filtering in jQuery allows you to select specific elements from a set of matched elements. It helps refine
selections based on conditions like position, attributes, or relationships.
Method Description
.filter(selector) Selects elements that match the selector.
.not(selector) Excludes elements that match the selector.
.first() Selects the first element.
.last() Selects the last element.
.eq(index) Selects the element at the given index.
.has(selector) Selects elements that contain the specified selector.
.is(selector) Checks if at least one element matches the selector.
The first() method returns the first element of the specified elements.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("div").first().css("background-color", "yellow");
});
</script>
</head>
<body
<h1>Welcome to My Homepage</h1>
<p>This is a paragraph.</p>
</div>
<br>
<div style="border: 1px solid black;">
</div>
<br>
</div>
</body>
</html>
The last() method returns the last element of the specified elements.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("div").last().css("background-color", "yellow");
});
</script>
</head>
<body>
<h1>Welcome to My Homepage</h1>
<p>This is a paragraph.</p>
</div>
<br>
</div>
<br>
</div>
</body>
</html>
The eq() method returns an element with a specific index number of the selected elements.
The index numbers start at 0, so the first element will have the index number 0 and not 1.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("p").eq(1).css("background-color", "yellow");
});
</script>
</head>
<body>
<h1>Welcome to My Homepage</h1>
</body>
</html>
The filter() method lets you specify a criteria. Elements that do not match the criteria are
removed from the selection, and those that match will be returned.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("p").filter(".intro").css("background-color", "yellow");
});
</script>
</head>
<body>
<h1>Welcome to My Homepage</h1>
</body>
</html>
The not() method returns all elements that do not match the criteria.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(function(){
$("p").not(".intro").css("background-color", "yellow");
});
</script>
</head>
<body>
<h1>Welcome to My Homepage</h1>
</body>
</html>
Relative Position: Setting the top, right, bottom, and left properties
of an element with position: relative; property will cause it to adjust
from its normal position. The other objects or elements will not fill the
gap.
Syntax:
position: relative;
Absolute Position: An element with position: absolute; will cause it to
adjust its position with respect to its parent. If no parent is present,
then it uses the document body as parent.
position: absolute;
Fixed Position: Position: fixed; property applied to an element will
cause it to always stay in the same place even if the page is scrolled.
To position the element we use top, right, bottom, left properties.
Why Use Callback Functions?
o In JavaScript statements are executed line by line, but with effects, the next line of code
can run even before the effect is fully finished. This can lead to errors.
o To prevent such issues, you can create a callback function. It ensures that your code
runs only after the effect is complete.
o Remember to use them when dealing with asynchronous operations or effects to
maintain code correctness and avoid unexpected behavior.