Professional Documents
Culture Documents
FSWDUNIT2
FSWDUNIT2
FSWDUNIT2
1. Script is a set of instruction used to perform certain task either on server side or client
side.
2. JavaScript is a subset of java.
JavaScript Types
JavaScript Type Details
Internal JavaScript code is placed in the head and body section of an HTML
page.
External JavaScript codes are stored in separate external file using the .js
extension
(Ex: external.js).
Printing in JavaScript
Method Writing into Example Program
innerHTML HTML <p id="demo"></p>
element <script>
document.write HTML output document.getElementById("demo").innerHTML = 5 +
() 6;
an alert box document.write(5 + 6);
window.alert() window.alert(5 + 6);
console.log(5 + 6);
</script>
<!—Print page 🡪
FULL STACK WEB DEVELOPMENT
Output 11 11
Arithmetic Operators
Operator Description Operator Description Operator Description
+ Addition / Division -- Decrement
- Subtraction % Modulus (Gives Remainder)
* Multiplication ++ Increment
Assignment Operators
Operator Description Same As Operator Description Same As
= x=y x=y *= x *= y x=x*y
+= x += y x=x+y /= x /= y x=x/y
-= x -= y x=x-y %= x %= y x=x%y
Logical Operators
Operator Description Output
&& logical and True / False based on condition
|| logical or True / False based on condition
! logical not True / False based on condition
Comparison Operators
Operator Description Output Operator Description Output
greater than or True /
== equal to True / False >=
equal to False
less than or True /
!= not equal to True / False <=
equal to False
ternary True /
> greater than True / False ?:
operator False
< less than True / False
Conditional Statements are of 4 types (If, Else, Else if and switch).They were
Conditional
Syntax Example Output
Statement
FULL STACK WEB DEVELOPMENT
if (condition) {
If if (3>2) { document.write("3 is big"); } 3 is big
Code }
if (condition1) if (2>3)
{ code } { document.write("2 is big"); }
Else if else if else if (3>2) { document.write("3 is big"); 3 is big
(condition2) }
{ code } else {document.write("Both are same");
else {code } }
switch(2)
switch(expression)
{
{
case 1: code
case 1: document.write("Selected
block; break;
Case2"); }; break;
switch case 1: code Selected Case2
case 2: document.write("Selected
block; break;
Case2"); }; break;
default: code
default:document.write("Selected Case
block; break;
Default"); }; break;
}
}
While Loop
It is a set of Lines of code to be executed till it meets a certain condition. But I this loop first
checks the condition of the loop and then it enters into the code block. It the condition is
false it comes out of the loop.
For Loop
It is used to repeat a Block / Lines of code to be executed till it meets a certain condition.
But in this loop first it enter into the code block and then increment / decrements the
counters and then checks the condition of the loop till the condition is false it comes out of
the loop.
Functions
It is a set of instructions used to perform a particular task & function code is written inside
the script tag.
Program Output
No Arguments <script>
function hai() { window.alert("hi"); }
</script> hi in a window
<input type="button" value="click me"
onclick="hai();"/>
FULL STACK WEB DEVELOPMENT
Arguments <script>
function getcube(number){
alert(number*number*number);
}
</script> 64
<form>
<input type="button" value="click"
onclick="getcube(4)"/>
</form>
Return Value <script>
function Info(){
return "wisdom materials"; wisdom
} materials
document.write(Info());
</script>
JavaScript Object
It is a real world thing / entity having state and behavior (properties and method).
Example: car, pen, chair, glass, keyboard, monitor etc. JavaScript is an object-based
language. Everything is an object in JavaScript. Here we don't create class to get the
object. But, we direct create objects.
We need to create function with arguments. Each argument value can be assigned in the
current object by using this keyword. This keyword refers to the current object.
<script> 3 prasad 30000
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(3,"prasad",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
JavaScript array
It is an object that represents a collection of similar type of elements. There are 2 ways to
construct array in JavaScript.
1. By array literal. 2. By creating instance of Array directly (using new keyword).
<p id="demo"></p>
<script>
var cars = ["maruti", "mahindra", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script>
Output JavaScript Arrays: JavaScript array elements are accessed using numeric
indexes (starting from 0).
maruti
Associative Arrays
Syntax Arrays with named indexes are called associative arrays (or hashes). JavaScript
support arrays with numbered indexes but not named indexes.
Example <h2>JavaScript Associative Arrays</h2>
<p id="demo"></p>
<script>
var person = [];
person[0] = "prasad";
person[1] = "wisdom";
person[2] = 46;
document.getElementById("demo").innerHTML =
FULL STACK WEB DEVELOPMENT
JavaScript String
The JavaScript string is an object that represents a sequence of characters. Create string in
2 way uisng JavaScript.
1. By string literal. 2. By string object using new keyword
toLocaleUpperCase( It converts the given string into uppercase letter on the basis of
) host?s current locale.
toString() Provides a string representing the particular object.
valueOf() Provides the primitive value of string object.
split() Splits a string into substring array, then returns that newly created
array.
trim() trims the white space from the left and right side of the string.
Example
Program Output
<script> S
//charAt(index) Method
var str="wisdom materials";
document.write(str.charAt(2)+ "<br>");
//toLowerCase() Method
var s6="WISDOM";
document.write(s6.toLowerCase()+"<br>");
//toLowerCase() Method
var s7="wisdom materials";
document.write(s7.toUpperCase()+"<br>");
Example
Program Output
Current Date and Time: Current Date and Time:
<p id="txt"></p> Tue Jan 30 2024 14:29:31 GMT+0530
<script> (India Standard Time)
var today=new Date();
document.getElementById('txt').innerHTML=toda
y;
</script>
JavaScript Methods
<script> Date:25
var d = new Date("2021-03-25") FullYear:2021
document.write("Date:"+d.getDate()+"<br>"); Month:2
document.write("FullYear:"+d.getFullYear()+"<br Hours:5
>"); Minutes:30
document.write("Month:"+d.getMonth()+"<br>") Seconds:0
;
document.write("Hours:"+d.getHours()+"<br>");
document.write("Minutes:"+d.getMinutes()+"<br
>");
document.write("Seconds:"+d.getSeconds()+"<br
>");
</script>
JavaScript Math
The JavaScript math object provides several constants and methods to perform
mathematical operation. Unlike date object, it doesn't have constructors.
Methods returns
abs() Absolute value of the given number.
acos() arccosine of the given number in radians
asin() Arcsine of the given number in radians.
atan() arc-tangent of the given number in radians
cbrt() cube root of the given number
ceil() a smallest integer value, greater than or equal to the given number.
cos() Cosine of the given number.
cosh() Hyperbolic cosine of the given number.
exp() exponential form of the given number
floor() Largest integer value, lower than or equal to the given number.
hypot() square root of sum of the squares of given numbers
log() Natural logarithm of a number.
max() Maximum value of the given numbers.
min() Minimum value of the given numbers.
pow() Value of base to the power of exponent.
random() random number between 0 (inclusive) and 1 (exclusive)
round() closest integer value of the given number
sign() the sign of the given number
sin() sine of the given number
sinh() Hyperbolic sine of the given number.
sqrt() square root of the given number
tan() Tangent of the given number.
tanh() Hyperbolic tangent of the given number.
trunc() An integer part of the given number.
JavaScript Boolean
Theory JavaScript Boolean is an object that represents value in two states: true or false.
You can create the JavaScript Boolean object by Boolean() constructor.
Boolean b=new Boolean(value);
The default value of JavaScript Boolean object is false.
Exampl <script>
e document.write(10<20);//true
document.write(10<5);//false
</script>
addEventListener() method.
Progra <p> addEventListener() method </p>
m <button id = "btn"> Click me </button>
<p id = "para"></p>
<script>
document.getElementById("btn").addEventListener("click", fun);
FULL STACK WEB DEVELOPMENT
function fun() {
document.getElementById("para").innerHTML = "Hi Wisdom materials";
}
</script>
Output Hi Wisdom materials
Radio
<script>
function tv()
{
var tbv=document.f1.g.value;
alert("Text Validation fucntion");
if(tbv=="male" || tbv=="female" )
alert("true");
else
alert("false / Choose a proper gender");
}
</script>
<form name="f1">
male<input type="radio" name="g" value="male" /><br>
female<input type="radio" name="g" value="female"
/><br>
</form>
Select
<script>
function tv()
{
var tbv=document.f1.country.value;
alert(tbv);
if(tbv==0)
{ alert("Choose a Country / False"); return False; }
else
{ alert(tbv); return true; }
FULL STACK WEB DEVELOPMENT
}
</script>
</form>
Gmail
<script language="javascript" type="text/javascript">
function Validate()
{
var t1 = document.f1.t4.value;
if (t1.match("@gmail.com"))
{alert(t1); return true;}
else
{
alert("Enter a proper Gmail");
return false;
}
}
</script>
Gmail Validation<br>
<form name="f1" onsubmit="return Validate()" action="http://www.google.com/"
method="post" >
Email : <input type="text" name="t4" id="email2"/><br>
<input type="reset" value="reset" name="reset" />
<input type="submit" value="submit" name="submit" />
</form>
(client-side) to send data to, and retrieve data from, a server-side script. This all happens in
the background so data can be updated on the current page without requiring the user to
load a new page. AJAX use text or JSON text to transport data but not XML.
Example
Ajax.html <div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>
ajax_info.tx <h1>AJAX</h1>
t <p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers from a web page.</p>
<p>AJAX stands for Asynchronous JavaScript And XML.</p>
FULL STACK WEB DEVELOPMENT
Property Description
onreadystatechange Defines a function to be called when the readyState property
changes
readyState Holds the status of the XMLHttpRequest.
0: request not initialized, 1: server connection established, 2: request
received, 3: processing request, 4: request finished and response is
ready
status 200: "OK", 403: "Forbidden", 404: "Page not found", For a
complete list go to the Http Messages Reference
statusText Returns the status-text (e.g. "OK" or "Not Found")
<table id="demo"></table>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Artist</th><th>Title</th></tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) {
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>
cd_catalog.xm <?xml version="1.0" encoding="UTF-8"?>
l <CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
</CATALOG>
FULL STACK WEB DEVELOPMENT
$hint = "";
Code explanation
First, check if the input field is empty (str.length == 0). If it is, clear the content of the
txtHint placeholder and exit the function. However, if the input field is not empty, do the
following:
<script>
function showCustomer(str) {
var xhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "getcustomer.php?q="+str, true);
xhttp.send();
}
</script>
</body>
</html>
getcustomer.ph AJAX Database Example
p AJAX can be used for interactive communication with a database.
<?php
$mysqli = new mysqli("servername", "username", "password",
"dbname");
if($mysqli->connect_error) {
exit('Could not connect');
}
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $_GET['q']);
$stmt->execute();
FULL STACK WEB DEVELOPMENT
$stmt->store_result();
$stmt->bind_result($cid, $cname, $name, $adr, $city, $pcode, $country);
$stmt->fetch();
$stmt->close();
echo "<table>";
echo "<tr>";
echo "<th>CustomerID</th>";
echo "<td>" . $cid . "</td>";
echo "<th>CompanyName</th>";
echo "<td>" . $cname . "</td>";
echo "<th>ContactName</th>";
echo "<td>" . $name . "</td>";
echo "<th>Address</th>";
echo "<td>" . $adr . "</td>";
echo "<th>City</th>";
echo "<td>" . $city . "</td>";
echo "<th>PostalCode</th>";
echo "<td>" . $pcode . "</td>";
echo "<th>Country</th>";
echo "<td>" . $country . "</td>";
echo "</tr>";
echo "</table>";
?>
Output
jQuery
Jquery Jquery is JavaScript library, Subset of java, free, open-source software and
lightweight, "write less, and do more".
Developed by John Resig at BarCamp NYC in January 2006
jQuery HTML manipulation, DOM manipulation, DOM element selection, CSS
Features manipulation, Effects and Animations, Utilities, AJAX, HTML event
methods, JSON Parsing, Extensibility through plugins
Used by Google, Microsoft, IBM, Netflix
Applications Show & Hide P tag, Fade, SlideDown and Slideup, Animation, Chaining
etc.
FULL STACK WEB DEVELOPMENT
<script type="text/javascript">
$(document).ready(function () {
$("#hide").click(function () { $("div").hide(); });
$("#show").click(function () { $("div").show(); });
});
</script>
jQuery Selectors
jQuery selectors use factory function ($()) find / select HTML elements based on their id,
classes, attributes, types and much more from a DOM. $()= factory function uses the three
basic building blocks while selecting an element in a given document.
Selector Description
Tag It represents a tag name available in the DOM. Example: $('p') selects all
Name paragraphs'p'in the document.
It represents a tag available with a specific ID in the DOM. Example:
Tag ID $('#real-id') selects a specific element in the document that has an ID of real-id.
Tag It represents a tag available with a specific class in the DOM. Example:
Class: $('real-class') selects all elements in the document that have a class of real-class.
<script>
$(document).ready(function(){
$("h2").click(function(){
$(".test1").hide();
});
});
</script>
<b class="test1">class selector example hidden</b>
<h2>click Class Selector </h2><br><br><br><br>
<script>
$(document).ready(function(){
$("pre").click(function(){
$("i").css("background-color", "red");
});
});
</script>
<i>Element Selector example hidden</i>
<pre>Click me to pre tag to hide </pre>
Selector
Selector Example It will select
* $("*") all elements.
#id $("#firstname") element with id="firstname"
.class $(".primary") all elements with class="primary"
FULL STACK WEB DEVELOPMENT
jQuery Events
All the different visitors' actions that a web page can respond to are called events. Events
examples: A mouse click, An HTML form submission, A web page loading, A keystroke on
the keyboard, Scrolling of the web page etc.
Form Events
focus blur
<script src=" jquery.min.js"></script> <script src=" jquery.min.js"></script>
<script> <script>
$(document).ready(function(){ $(document).ready(function(){
$("input").focus(function(){ $("input").focus(function(){
$(this).css("background-color", $(this).css("background-color", "yellow");
"yellow"); });
}); $("input").blur(function(){
$("input").blur(function(){ $(this).css("background-color", "green");
$(this).css("background-color", });
"green"); });
}); </script>
}); Name: <input type="text"
</script> name="fullname"><br>
Name: <input type="text" Email: <input type="text" name="email">
name="fullname"><br>
FULL STACK WEB DEVELOPMENT
Example: When a click event fires on a <p> element; hide the current <p> element:
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").on({
mouseenter: function(){
$(this).css("background-color", "lightgray");
},
mouseleave: function(){
$(this).css("background-color", "lightblue");
},
click: function(){
$(this).css("background-color", "yellow");
}
});
});
</script>
<p>Click or move the mouse pointer over this paragraph.</p>
Output Change paragraph background color on mouse hover.
elements. Content Manipulation: The html( ) method gets the html contents (innerHTML)
of the first matched element. Syntax: selector.html()
Examples
DOM To Add Elements DOM to Replace Elements
<script src=" jquery.min.js"> <script src=" jquery.min.js"></script>
</script> <script>
<script> $(document).ready(function()
$(document).ready(function() { {
$("div").click(function () { $("div").click(function () {
var content = $(this).html(); $(this).replaceWith("content replaced JQuery is
$("#result").text( content ); Great");
}); }); }); });
</script> </script>
<span id = "result"> </span> <span id = "result"> </span>
<div id = "division">Click to replace div
<div id = "division">Click to Add content</div>
content</div>
Click to Add content content replaced JQuery is Great
Click to Add content
Removing DOM Elements selector.remove([expr]) or selector.empty()
The empty( ) method remove all child nodes from
the set of matched elements where as the
method remove( expr ) method removes all
matched elements from the DOM.
<script>
$(document).ready(function()
{
$("div").click(function ()
{
$(this).remove( );
}); });
</script>
<style>div{ margin:10px;padding:12px;
border:2px solid #666; width:30px;} </style>
<p>Click on any square below:</p>
<span id = "result"> </span>
<div class = "div" style =
"background-color:blue;"></div>
<div class = "div" style =
"background-color:green;"></div>
<div class = "div" style =
"background-color:red;"></div>
JQuery Effects:
With jQuery,we can hide and show HTML elements with the hide() and show() methods.
FULL STACK WEB DEVELOPMENT
$(document).ready(function(){
$("div").click(function(){
$("p").show();
});
});
</script>
<div>Show function</div>
<b>Hide function</b>
<p>Hide / show</p>
jQuery toggle between hiding and showing an element
toggle(): with the toggle() method.
Syntax:$(selector).toggle(speed,callback);
speed parameter take values:”slow”,”fast”,or
milliseconds. callback parameter is a function
to be executed after toggle() completes.
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").toggle();
});
});
</script>
<button>Toggle between hiding and showing
the paragraphs</button>
<p>This is a paragraph with little content.</p>
<p>This is another small paragraph.</p>
jQuery Fading Methods:
With jQuery you can fade an element in and out of visibility.
Jquery has the following fade methods: fadeIn(), Fadeout(), fadeToggle(), fadeTo()
$(selector).fadeIn(speed,callback);
Program Output
FULL STACK WEB DEVELOPMENT
jQuery Sliding Methods:With jQuery you can create a sliding effect on elements.
jQuery has the following slide methods: slideDown(), slideUp(), slideToggle()
Syntax :$(selector).slideDown(speed,callback); - speed - milliseconds
Program Output
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown("slow");
});
});
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideUp("slow");
});
});
</script>
<style>
#panel, #flip {padding: 5px;text-align: center;
background-color: #e5eecc;border: solid 1px #c3c3c3;}
#panel {padding: 50px;display: none;}
</style>
<div id="flip">Click to slide down panel</div>
<div id="panel">Hello world!</div>
FULL STACK WEB DEVELOPMENT
jQuery Animations
The Jquery animate() method is used to create custom animations.
Syntax :$(selector).animate({params},speed,callback);
params Defines the CSS properties to be animated.
speed Milliseconds.
callback It is a function to be executed after the animation completes.
Examples
Start Animation(Click to move Rect) Output
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({left: '250px'});
});
});
</script>
<button>Start Animation(Click to move Rect)</button><br>
<div style="background:#98bf21;height:100px;
width:100px;position:absolute;"></div>
Program
Start Animation(Click to move Rect) Output
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',
height: '150px',
width: '150px'
});
});
});
</script>
<button>Start Animation by changing multiple properties of
Rect</button>
<div
style="background:#98bf21;height:100px;width:100px;position:absol
ute;"></div>
jQuery animate() - Using Relative Values: Output
It is done by putting += or -= in front of the values:
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
FULL STACK WEB DEVELOPMENT
left: '250px',
height: '+=150px',
width: '+=150px'
});
});
});
</script>
<button>Start Animation using relative values</button>
<div style="background:#98bf21;height:100px;
width:100px;position:absolute;"></div>
jQuery animate() - Using Pre-defined Values: Output
We can even specify a properties animation values as “show”,,”hide”,
or “toggle”:
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
height: 'toggle'
});
});
});
</script>
<button>Start Animation</button>
<div style="background:#98bf21;height:100px;
width:100px;position:absolute;"></div>
Uses Queue Functionality Output
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"
></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var div = $("div");
div.animate({height: '300px', opacity: '0.4'}, "slow");
div.animate({width: '300px', opacity: '0.8'}, "slow");
div.animate({height: '100px', opacity: '0.4'}, "slow");
div.animate({width: '100px', opacity: '0.8'}, "slow");
});
});
</script>
<button>Start Animation</button>
<div
style="background:#98bf21;height:100px;width:100px;position:absol
ute;"></div>
Start Animation to change font size Output
FULL STACK WEB DEVELOPMENT
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"
></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var div = $("div");
div.animate({left: '100px'}, "slow");
div.animate({fontSize: '3em'}, "slow");
});
});
</script>
<button>Start Animation to change font size</button>
<div
style="background:#98bf21;height:100px;width:200px;position:absol
ute;">HELLO</div>
stop() : The jQuery stop() method is used to stop an animation or effect before it is finished.
The stop() method works for all jQuery effects functions,including sliding,fading and
custom animations.
Syntax:$(selector).stop(stopAll,goToEnd);
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. goToEnd parameter specifies whether or
not to complete the current animation immediately. Default is false.
jQuery Traversing
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
FULL STACK WEB DEVELOPMENT
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>
Traversing the DOM:
jQuery provides a variety of methods that allow us to traverse the DOM.
The largest category of traversal methods are tree-traversal.
All parents
<style>
.ancestors * { display: block;border: 2px solid lightgrey;color: lightgrey;
padding: 5px;margin: 15px;}</style>
<script src=" jquery.min.js"></script>
<script>
$(document).ready(function(){
$("span").parents().css({"color": "red", "border": "2px solid red"});
});
</script>
$(document).ready(function(){
$("span").parentsUntil("div").css({"color": "red", "border": "2px solid red"});
});
</script>
<body class="ancestors"> body (great-great-grandparent)
<div style="width:500px;">div (great-grandparent)
<ul>ul (grandparent)
<li>li (direct parent)
<span>span</span>
</li>
</ul>
</div>
</body>
<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>
<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>
<script>
$(document).ready(function(){
$("h2").nextUntil("h6").css({"color": "red", "border": "2px
solid red"});
});
</script>
<body class="siblings">
<div>div (parent)
<p>p</p>
<span>span</span>
<h2>h2</h2>
<h3>h3</h3>
<h4>h4</h4>
<h5>h5</h5>
<h6>h6</h6>
<p>p</p>
</div>
</body>
<script>
$(document).ready(function(){
$("h2").nextAll().css({"color": "red", "border": "2px solid red"});
});
</script>
<body class="siblings">
<div>div (parent)
<p>p</p>
<span>span</span>
<h2>h2</h2>
<h3>h3</h3>
<p>p</p>
</div>
</body>
jQuery first() Method: It returns the first element of the specified elements.
FULL STACK WEB DEVELOPMENT
<body>
<h1>My Homepage</h1>
<p>Paragraph.</p>
<div style="border: 1px solid black;">
<p>Paragraph1 in div.</p>
<p>Paragraph2 in div.</p>
</div><br>