Unit-3
Java Script and JQuery
History of Java script
• JavaScript was created in 10 days in may 1995 by
Brendan Eich, then working at Netscape and now
Mozilla.
• The original name of JavaScript was mocha(name chosen
by founder of Netscape)
• In September 1995, name changed to LiveScript .
• Again in December 1995, name changed to JavaScript.
Overview Of JavaScript
• Java script is high level, un-typed interpreted
client-side scripting language.
• Designed to add interactivity to HTML pages
• Lightweight scripting programming language
• Interpreted and embedded directly into HTML
pages
Overview Of JavaScript
• JavaScript gives HTML designers a programming tool
pages
• JavaScript can put dynamic text into an HTML page
• JavaScript can react to events
• JavaScript can read and write HTML elements
• JavaScript can be used to validate data
• JavaScript can be used to create cookies
Where to Put the JavaScript
• JavaScript executes immediately while the page loads into
the browser.
• This is not always what we want. Sometimes we want to
execute a script when a page loads, or at a later event, such as
when a user clicks a button.
• When this is the case we put the script inside a function,
head, body and both in head and body.
Primitives
JS has 5 primitives :
1. numbers: 2, 3.7, -7
2. string: “hello”, “123”
3. booleans: true , false
4. null: variables whose value are set to null
5. undefined: variables which are declared but not
initialized
JavaScript Variables
● hold values or expressions
● Variable names are case sensitive
● Variable names must begin with a letter or the underscore character
● declare JavaScript variables with the var statement:
var name; (deceleration)
var age;
age = 23; (initialization)
var city= “Kathmandu”;( declaration and initialization)
JavaScript Variables
Way to include java script in html
1. Internal:
JavaScript code must be inserted between
<script> and </script>tags.
2. External
An external JavaScript file must be saved by .js extension. It is
recommended to embed all JavaScript files into a single file. It
increases the speed of the webpage.
Syntax: <script src="URL">
Operators
● operators are used to perform an operation
● types of operator in JS are:
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical/boolean Operators
5. String Operators
Control Statement
• Branching statement
• Looping statement
Pop-up Boxes
Java script has three pop up boxes.
1. Alert box
2. Confirm box
3. Prompt box
Alert box
● used if you want to make sure information
comes through to the user
● the user will have to click "OK" to proceed
● Syntax :alert("sometext");
Confirmation Box
● used if we want the user to verify or accept
something
● have to click either "OK" or "Cancel" to proceed
● If the user clicks "OK", the box returns true
● If the user clicks "Cancel", the box returns false
● Syntax : confirm("sometext");
Prompt Box
● used when you want user to input a value before
entering a page
● user will have to click either "OK" or "Cancel" to
proceed after entering an input value
● If the user clicks "OK" the box returns the input value
● If the user clicks "Cancel" the box returns null
● Syntax: prompt("sometext","defaultvalue");
Java script Function
● Function is simply a block of code with a name, which allows
the block of code to be called by other components in the
scripts to perform certain tasks.
● Functions can also accept parameters that they use complete
their task.
● JavaScript actually comes with a number of built-in functions
to accomplish a variety of tasks.
● We can also create custom build function.
General syntax for creating a function in
JavaScript is as follows:
function name_of_function(arg1,arg2,...,argn)
{
//block of codes
}
Function is executed when
• Function is invoked from another js function.
• Function is attached with some event and event occurs
Returning value:
• Function may return value using return keyword
• Function can only return one value
• Once a function returns a value, control returns back
to caller.
Events
● An HTML event can be something the browser does, or something a user
does.
● Here are some examples of HTML events:
An HTML web page has finished loading
An HTML input field was changed
An HTML button was clicked
When user clicks mouse
When image has been loaded
When mouse moves over an element
When html form is submitted
When user stroke a key
Event
Event Handling:
• Event handling is mechanism that controls the event and
sometime we want to execute a java script when an
event occurs such as when user clicks button
• Events are normally used in combination with function
and function cannot be executed before event occurs
• Syntax:<element event attribute="some JavaScript">
Event attribute:
• Onload: A page or image is finished loading
• Onupload: The user exits the page
• Onblur: An element loses focus
• Onchange: The content of field change.
• Onclick: Mouse click on object.
• Ondbclick: Mouse double click on object
• Onfocus: An element get focus.
• Onselect: Text is selected
• Onkeydown: A keyboard key is pressed.
• Onkeypress: A keyboard key is pressed or held down.
• Onmousemove: A mouse is moved
• Onmouseout: A mouse is moved off an element
• Onmouseover: A mouse is moved over an element.
• Onmouseup: A mouse is released.
Output:
Java Script Object
• Java script object is an entity having state and behavior (properties and
method).
• In java script, everything is an object.
• Java script is template based not class base, here class cannot be created to
get object, but direct create object.
• An object is unordered collection of properties, each of which has a name
and value
• There are three ways to create an object
– By object literal
– By creating instance of object directly(using new keyword)
– By using an object constructor.
JavaScript Object by object literal
Syntax: object={property1:value1,property2:value2.....propertyN:valueN}
Example:
<html>
<body>
<script>
student={roll:102,name:"Shyam ",address:"ktm"}
document.write(student.roll+" "+student.name+" "+student.address);
</script>
</body>
</html>
By creating instance of Object
Syntax: var objectname=new Object();
Example:
<html>
<body>
<script>
var emp=new Object();
emp.id=101;
emp.name=“Taveeta Lohani";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>
By using an Object constructor
• Here, user need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword.
Example:
<html>
<body>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,“Taveeta Lohani",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
</body>
</html>
Java script object
• There are mainly six object used in java script.
1. Array
2. String
3. Math
4. Date
5. Number
6. Boolean
1. Arrays:
• An array is ordered set of data element which can be
accessed through single variable.
• Java script array is an object that represents collection of
variable of similar type.
• There are several way to define arrays in JS
– Var <arr_name> = [value 1, value 2,…..,value n];
– Var <arr_name> = new Array();
– Var <arr_name> = new Array(value 1, value 2,…..,value n);
JavaScript Array Methods:
Concat(): It returns a new array object that contains two or more
merged arrays.
Find(): It returns the value of the first element in the given array that the
specified condition.
Pop(): It removes and returns the last element of an array.
Push(): It adds one or more elements to the end of an array.
Reverse(): It reverses the elements of given array.
Sort(): It returns the element of the given array in a sorted order.
Slice():It returns a new array containing the copy of the part of the given
array
Example:
<html>
<body>
<script>
var emp=[“Taveeta",“supriya",“Tekendra"];
for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br/>");
}
</script>
</body>
</html>
2.String object
• String is a set of character enclose in pair of double
quotes.
• Java script string is an object that represents a
sequence of character.
Syntax:
Var <string name>=“string value”;
Var <string name>= new string(string value);
• Property: length.
JavaScript String Methods:
charAt(): It provides the char value present at the specified index.
Concat(): It provides a combination of two or more strings.
Indexof():It provides the position of a char value present in the
given string.
toLowerCase():It converts the given string into lowercase letter.
toUpperCase(): It converts the given string into uppercase letter.
Trim(): remove leading and tailing whitespace.
Slice(): returns substring.
Example:
<html>
<body>
<script>
var str = “TRIBHUVAN UNIVERSITY";
document.writeln(str.toLowerCase());
</script>
</body>
</html>
Math object:
Java script math object provides several constants and methods to perform
mathematical operation.
Method:
– Math.sqrt()
– Math. Random()
– Math.floor()
– Math. Ceil()
– Math.abs()
– Math.min()
– Math.max()
– Math.sin()
– Math.cos()
– Math.tan()
– Math.exp()
Date object:
• Java script date object is used to obtain a date and time .
• This date and time is based on computer local time
• Use different date constructor to create data object.
• Syntax:
– Date()
– Date(miliseconds)
– Date(datestring)
– Date(year, month,day,h,m,s,ms)
Methods:
– getFullyear()
– getMonth()
– getDate()
– getDay()
– getHours()
– getMinutes()
– getSeconds()
– getMiliseconds()
Example:
<html>
<body>
Current Time: <span id="txt"></span>
<script>
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
</script>
</body>
</html>
Browser object model
• The browser object model is used to interact
with browser.
• The default object of browser is window.
Window object:
• Window object represents a window in browser.
• An object of window is created automatically by the user
• Method: alert(),confirm(), prompt(), setTimeout(),open(),close()
History objects:
• Java script history object represents an array of url’s visited by user.
• By using this object we can load previous, forward or particular page.
• Property: length
• Method: forward(),back(),go()
Navigator object:
• It is used for browser detection
• It is used to get browser information such as appName, appCodeName,
userAgent etc.
• Property: appName, appVersion, appCodeName, Language, userAgent etc
• Mtheod: javaEnabled()
Screen Object:
• It hold information about browser screens
• It can be used to display screen width, height, color depth pixel depth etc.
• Property: width ,height, availwidth, availheight, colaorDepth etc.
Document Object model
• The document object represents the whole html document .
• The document object model (DOM) is a platform and language neutral interface
that allows programs and scripts to dynamically access and update the content,
structure and style of document.
• HTML DOM is standard object model for HTML
• The DOM says:
– The entire document is document node
– Every HTML element is an element node
– Text in html elements are text nodes
– Every html attribute is an attribute node
– Comments are comment node.
HTML DOM properties:
Some DOM properties are
X.innerHTML: The text value of x
X.innerText: Sets or returns the text content of X
X.nodeName: The name of x
X.nodeValue: The value of x
X.parentNode: The parent of node X
X.childNode: The child node of x.
X.attribute: The attribute of x
HTML DOM Methods:
– Write(“string”): writes the given string on the document.
– Writeln(“string”): writes the given string on the document with newline
character at the end.
– getElementById(): returns the element having the given id value.
– getElementsByName():returns all the elements having the given name
value.
– getElementsByTagName():returns all the elements having the given tag
name.
– getElementsByClassName():returns all the elements having the given
class name.
Example :getElementById():
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to change the text in this paragraph.</p>
<button onclick="myFunction()">Click Me</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</body>
</html>
Validation
• Validation is process of ensuring that form’s values are correct or
not.
• Form validation is process of checking that form has been filled
in correctly before it is processed.
• Some type of validation are:
– Preventing blank values.
– Ensuring the type of values
– Ensuring the format and range of values
– Ensuring that values fit together.
There are mainly two methods for validating form.
Client-side validation
• Validation is done before the form is submitted
• Can lead to better user experience but not secure
• Faster and easier to do.
• client-side validation usually done using JavaScript and VBScript.
• Server-side validation:
• Validation is done after the form is submitted
• Server-side validation is more secure but often more tricky to code.
• it also increases load of server computer, it is slower.
• Server-side validation is done usually done using php, asp and jsp etc.
Form Validation - Checking for Non-Empty
Check to see if a given HTML input is empty or not.
Example:
<!DOCTYPE html>
<html>
<head>
<title>validation Example:</title>
<script type='text/javascript'>
function notEmpty()
{
var v= document.getElementById("elem").value;
if(v.length == 0)
{
alert("Field should not be empty:");
}
}
</script>
</head>
<body>
<form>
Required Field: <input type="text" id="elem"/>
<input type="button" onclick="notEmpty()" value="Check"/>
</form>
</body>
</html>
Form Validation - Checking for All Numbers
• The quickest way to check if an input's string value is all numbers is to use a regular expression /^[0-
9]+$/ that will only match if the string is all numbers and is at least one character long.
<!DOCTYPE html>
<html>
<head>
<title>validation Example:</title>
<script type='text/javascript'>
function validate()
{
var patt=/^[0-9]+$/;
var v= document.getElementById('elem').value;
if(v.match(patt))
alert("valid entry");
else
alert("Invalid entry");
}
</script>
</head>
<body><form>
Required Field: <input type="text" id="elem"/>
<input type="button" onclick="validate()" value="Check"/>
</form>
</body></html>
Form Validation - Checking for All Letters
• regEX:/^[a-zA-Z]+$/
Example:
<!DOCTYPE html>
<html>
<head>
<title>validation Example:</title>
<script type='text/javascript'>
function validate()
{
var patt=/^[a-zA-Z]+$/;
var v= document.getElementById('elem').value;
if(v.match(patt))
alert("valid entry");
else
alert("Invalid entry");
}
</script>
</head>
<body><form>
Required Field: <input type="text" id="elem"/>
<input type="button" onclick="validate()" value="Check"/>
</form>
</body></html>
Form Validation - Restricting the Length
Example :
<!DOCTYPE html>
<html>
<head>
<title>validation Example:</title>
<script type='text/javascript'>
function validate()
{
var minlen=6;
var v= document.getElementById('elem').value;
if(v.length<minlen)
alert("User ID must have at least 6 Characters"); ;
else
alert("valid entry");
}
</script>
</head>
<body>
<form>
Required Field: <input type="text" id="elem"/>
<input type="button" onclick="validate()" value="Check"/>
</form>
</body>
</html>
Form Validation - Selection Made
Example:
<!DOCTYPE html>
<html>
<head>
<title>validation Example:</title>
<script type='text/javascript'>
function validate()
{
var si=document.getElementById('con').selectedIndex;
var v= document.getElementById('con').options[si].text;
if(v=="Please Choose")
alert("You must choose the country");
else
alert("Your Country is:"+v);
}
</script>
<form>
Select Country: <select id='con'>
<option>Please Choose</option> <option>Nepal</option>
<option>India</option> <option>China</option>
</select>
<input type='button' onclick='validate()' value='Check'/>
</form>
</body>
</html>
Validating radio buttons: {
Example: if(gender[0].checked==true)
<!DOCTYPE html> alert("Male");
<html> else
<head> alert("Female");
<title>validation Example:</title> }}
<script type='text/javascript'> </script>
function validate() <form>
{ Select Gender:
var <input type=radio name='gen'>Male
gender=document.getElementsBy <input type=radio
Name("gen"); name='gen'>Female
if(gender[0].checked==false && <input type='button'
gender[1].checked==false) onclick='validate()'
{ value='Check'/>
alert("You must choose Gender"); </form>
} </body>
else </html>
Email validation:
Every email is made up for 5 parts:
1. A combination of letters, numbers, periods, hyphens, plus signs, and/or underscores
2. The at symbol @
3. A combination of letters, numbers, hyphens, and/or periods
4. A period
5. The top level domain (com, net, org, us, gov, ...)
Valid Examples:
ram@ntc.net
ram+nepal@gmail.com
ram-nepal@patan.edu.np
Invalid Examples:
@deleted.net - no characters before the @
free!dom@bravehe.art - invalid character !
shoes@need_shining.com - underscores are not allowed in the domain name
Example(Regular Expression):
<!DOCTYPE html>
<html>
<head>
<title>validation Example:</title>
<script type="text/javascript">
function validate()
{
var patt=/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
var v= document.getElementById("elem").value;
if(v.match(patt))
alert("valid Email");
else
alert("Invalid Email");
</script>
</head>
<body><form>
Email ID: <input type="text" id='elem'/>
<input type="button" onclick="validate()" value="Check"/>
</form>
</body>
</html>
Example (without regular expression)
<!DOCTYPE html>
<html>
<head>
<title>validation Example:</title>
<script type="text/javascript">
function validate()
{
var v= document.getElementById("elem").value
var atpos=v.indexof('@');
var dotpos=v.indexof('.');
if(atpos<1||dotpos>=v.length-2||dotpos<3)
alert("invalid Email");
else
alert("valid Email");
</script>
</head>
<body><form>
Email ID: <input type="text" id='elem'/>
<input type="button" onclick="validate()" value="Check"/>
</form>
</body>
</html>
Error Handling
● The try statement lets you test a block of code for
errors.
● The catch statement lets you handle the error.
● The throw statement lets you create custom errors.
● The finally statement lets you execute code, after
try and catch, regardless of the result.
Introduction to Jquery
• Developed by John Resign at Rochester institute of technology and
released in January 2006.
• Jquery is small light weight java script library that simplifies
programming with javascript.
• Jquery is fast, samall and feature-rich javascript library.
• JQuery is cross-platform.
• jQuery means "write less do more"
• It makes things like HTML document traversal and manipulation,
event handling, animation and AJAX.
How to use JQuery
• Download the jQuery library from jQery.com.
• Include jQuery from a CDN, like google
• The jQery library is a single javaScript file and refrence it with the <script> tag.
<head>
<script src="jquery-3.4.1.min.js"></script>
</head>
• It can also include from google CDN as
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
jQuery Syntax
• The jQuery syntax is tailor-made for selecting HTML elements and performing
some action on the element(s).
Basic syntax is:
$(selector).action()
A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)
Examples:
– $(this).hide() - hides the current element.
– $("p").hide() - hides all <p> elements.
– $(".test").hide() - hides all elements with class="test".
– $("#test").hide() - hides the element with id="test".
jQuery Selectors
• jQuery selectors allow you to select and manipulate HTML element(s).
element Selector
– The jQuery element selector selects elements based on the element name.
– Syntax: $(“element name”)
– Example: $(“p”)=selects all <p> elements in html document
#id Selector
– The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.
– Syntax: $(“#id_value”)
– Example: $(“#test”)=selects element with id=“test” in html document
.class Selector
– The jQuery .class selector finds elements with a specific class.
– Syntax: $(“.class_value”)
– Example: $(“.test”)=selects elements with class=“test” in html document
*selector
– Selects all elements
– Syntax : $(“*”)
Some other selector:
$(this) Selects the current HTML element
$("p.intro") Selects all <p> elements with class="intro“
$("p:first") Selects the first <p> element
$("ul li:first") Selects the first <li> element of the first <ul>
$("ul li:first-child") Selects the first <li> element of every <ul>
$("ul li:last-child") Selects the last <li> element of every <ul>
• Example:
JQuery Event
• jQuery events are the actions that can be detected by your web
application.
• They are used to create dynamic web pages.
• An event shows the exact moment when something happens.
• These are some examples of events.
– A mouse click
– An HTML form submission
– A web page loading
– A keystroke on the keyboard
– Scrolling of the web page etc.
Mouse Events
– click Form Events
– dblclick – submit
– mouseenter – change
– mouseleave – blur
Keyboard Events – focus
– keyup Document/Window Events
– keydown – load
– Keypress – unload
– scroll
– resize
Syntax for event methods
$("p").click(function(){
// action goes here!!
});
what should happen when the event fires
Example:
Jqery Effects
• jQuery enables us to add effects on a web page. jQuery effects
can be categorized into fading, sliding, hiding/showing and
animation effects.
Example (display effect) <p>
<!DOCTYPE html> <b>This is a little poem: </b><br/>
<html> Twinkle, twinkle, little star<br/>
<head> How I wonder what you are<br/>
<script src="jquery-3.3.1.min.js"></script> Up above the world so high<br/>
<script> Like a diamond in the sky<br/>
$(document).ready(function(){ Twinkle, twinkle little star<br/>
$("#hide").click(function(){ How I wonder what you are
$("p").hide(); </p>
}); <table>
$("#show").click(function(){ <tr><td>
$("p").show(); <button id="hide">Hide</button><td>
}); <td><button
$("#toggle").click(function(){ id="show">Show</button></td>
$("p").toggle(); <td><button
}); id="toggle">Toogle</button></td>
}); </tr>
</script> </table>
</head> </body>
<body> </html>
Example(fading effect) });
<!DOCTYPE html> </script>
<html> </head>
<head> <body>
<script src="jquery-3.3.1.min.js"></script> <p>See the fade effect example with
different parameters.</p>
<script> <button id="b1">fade in </button>
$(document).ready(function(){ <button id="b2"> fade out</button>
$("#b1").click(function(){ <button id="b3">fade
$("#div1").fadeIn(); toggle</button><br><br>
$("#div2").fadeIn("slow"); <div id="div1"
}); style="width:80px;height:80px;display:
none;background-color:red;"></div>
$("#b2").click(function(){
<div id="div2"
$("#div1").fadeOut();
style="width:80px;height:80px;display:
$("#div2").fadeOut("slow"); none;background-color:green;"></div>
});
$("#b3").click(function(){
$("#div1").fadeToggle(); </body>
$("#div2").fadeToggle("slow"); </html>
});
Example(slide effect) border: solid 1px #c3c3c3;
<!DOCTYPE html> }
<html>
<head> #panel {
<script src="jquery- padding: 50px;
3.3.1.min.js"></script> display: none;
<script> }
$(document).ready(function(){ </style>
$("#flip").click(function(){ </head>
$("#panel").slideDown("slow"); <body>
});
}); <div id="flip">Click to slide down
</script> panel</div>
<style> <div id="panel">Hello
#panel, #flip { world!</div>
padding: 5px;
text-align: center; </body>
Jquery HTML
• jQuery contains powerful methods for changing and manipulating
HTML elements and attributes.
Get Content - text(), html(), and val()
– Three simple, but useful, jQuery methods for DOM manipulation are:
– text() - Sets or returns the text content of selected elements
– html() - Sets or returns the content of selected elements (including HTML
markup)
– val() - Sets or returns the value of form fields
Example
Set Content - text(), html(), and val()
use the same three methods from the previous
page to set content:
– text() - Sets or returns the text content of selected
elements
– html() - Sets or returns the content of selected
elements (including HTML markup)
– val() - Sets or returns the value of form fields
Example: });
<!DOCTYPE html> </script>
<html> </head>
<head> <body>
<script
src="jquery-3.3.1.min.js"></script> <p id="test1">This is a paragraph.</p>
<p id="test2">This is another
<script> paragraph.</p>
$(document).ready(function(){
$("#btn1").click(function(){ <p>Input field: <input type="text"
$("#test1").text("Hello world!"); id="test3" value="something"></p>
});
$("#btn2").click(function(){ <button id="btn1">Set Text</button>
$("#test2").html("<b>Hello <button id="btn2">Set HTML</button>
world!</b>"); <button id="btn3">Set Value</button>
}); </body>
$("#btn3").click(function(){ </html>
$("#test3").val("Enetr input");
});
Add New HTML Content
• There are four jQuery methods that are used to add new content:
– append() - Inserts content at the end of the selected elements
– prepend() - Inserts content at the beginning of the selected elements
– after() - Inserts content after the selected elements
– before() - Inserts content before the selected elements
Remove Elements/Content
• To remove elements and content, there are mainly two jQuery
methods:
– remove() - Removes the selected element (and its child elements)
– empty() - Removes the child elements from the selected element
jQuery Manipulating CSS
• jQuery has several methods for CSS manipulation. We
will look at the following methods:
– addClass() - Adds one or more classes to the selected
elements
– removeClass() - Removes one or more classes from the
selected elements
– toggleClass() - Toggles between adding/removing classes
from the selected elements
– css() - Sets or returns the style attribute
Example: }
<!DOCTYPE html>
<html> .blue {
<head> color: blue;
<script }
src="jquery-3.3.1.min.js"></script> </style>
</head>
<script> <body>
$(document).ready(function(){
$("button").click(function(){ <div id="div1">This is some text.</div>
$("#div1").addClass("important <div id="div2">This is some text.</div>
blue");
<br>
});
});
<button>Add classes to first div
</script> element</button>
<style>
.important { </body>
font-weight: bold; </html>
font-size: xx-large;
Example(css() method)
<!DOCTYPE html> <p style="background-
<html> color:#ff0000">This is a
<head> paragraph.</p>
<script src="jquery- <p style="background-
3.3.1.min.js"></script> color:#00ff00">This is a
paragraph.</p>
<script>
<p style="background-
$(document).ready(function(){
color:#0000ff">This is a
$("button").click(function(){ paragraph.</p>
$("p").css({"background-color":
"yellow", "font-size": "200%"});
<p>This is a paragraph.</p>
});
});
<button>Set multiple styles for
</script> p</button>
</head>
<body> </body>
</html>
<h2>This is a heading</h2>
jQuery Traversing
• DOM traversing is one of the prominent features of the jQuery.
• To make the most it we need to understand the relationships between the elements in a DOM
tree.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML DOM Tree Sample</title>
<script src="jquery-1.12.4.min.js"></script>
</head>
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
</body>
</html>
Traversing Up the DOM Tree
• In logical relationships an ancestor is a parent,
grandparent, great-grandparent, and so on.
• jQuery provides the useful methods such
as parent(), parents() and parentsUntil() use
to traverse up in the DOM tree
Example(for parent() method)
Traversing Down the DOM Tree
• In logical relationships a descendant is a child,
grandchild, great-grandchild, and so on.
• jQuery provides the useful methods such
as children() and find() that you can use to
traverse down in the DOM tree
Example(For children() method)
jQuery Traversing Siblings
• In logical relationships siblings are those elements that share the
same parent.
• jQuery provides several methods such as
– siblings()
– next()
– nextAll()
– nextUntil()
– prev()
– prevAll()
– and prevUntil()
Example (For siblings() method