Lecture#9
Web Engineering
Instructor
•Seemab Karim
•Lecturer at Riphah International University
•Contact Email: [email protected]
Array In JS
• An array is a special variable, which can hold more than
one value in a linear way
Why Use Arrays?
• If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:
• let car1 = "Saab";
let car2 = "Volvo";
let car3 = "BMW";
• However, what if you want to loop through the cars and find a specific one? And
what if you had not 3 cars, but 300?
• The solution is an array!
• An array can hold many values under a single name, and you can access the
values by referring to an index number.
Creating an Array
• const array_name = [item1, item2, ...];
• const cars = ["Saab", "Volvo", "BMW"];
OR
• const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
Code Example
Loops in Array
•Array Methods
push(): Insert at end
pop(): delete from end
shift(): The shift() method removes the first array element
unshift(): The unshift() method adds a new element to an array
(at the beginning)
Array concat(): merge the arrays
Array Method’s Code
Array Methods cont…..
• splice():The splice() method can be used to add new items to an array:
array.splice(index, 0, newElement1, newElement2, ...);
Where,
index: where to insert
0: means delete 0 elements (i.e., just insert)
newElement1, newElement2, etc.: elements to insert
Deleting from a random position:
array.splice(index, deleteCount);
index: where to start deleting
deleteCount: how many elements to delete
Sort() and reverse() method
Assignment Questions
1: Create an array of 5 student names. Use a loop to print each name.
2: Store a set of numbers in an array. Write code to find the largest
number.
3: Store 6 numbers. Find the smallest and largest number using a loop.
4: Store a few numbers or strings. Display the array in
reverse order.
5: Ask the user for a number and check if it exists in an
array. Print “Found” or “Not Found”.
6: Create an array of numbers. Sort the array in
ascending order and print it.
7: Given an array with duplicate values, create a new
array with only unique values.
Functions in JS
Function
• Block of code that perform a specific task, and can be
invoked whenever needed
Function Declarations
function functionName()
{
// code to be executed
}
Can also be defined as
function functionName(para..1,para2..)
{
// code to be executed
}
Function Call
• Syntax
• functionName();
JS HTML DOM (Document Object Model)
• When a web page is loaded, the browser creates a Document Object
Model of the page.
• The HTML DOM model is constructed as a tree of Objects:
• With the HTML DOM, JavaScript can access and change all the
elements of an HTML document.
JS HTML DOM (Document Object Model)
• With the object model, JavaScript gets all the power it needs to create
dynamic HTML:
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page
What You Will Learn
In this lecture you will learn:
• How to change the content of HTML elements
• How to change the style (CSS) of HTML elements
• How to react to HTML DOM events
• How to add and delete HTML elements
What is the DOM?
• The DOM is a W3C (World Wide Web Consortium) standard.
• The DOM defines a standard for accessing documents:
• "The W3C 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 a document."
• The W3C DOM standard is separated into 3 different parts:
• Core DOM - standard model for all document types
• XML DOM - standard model for XML documents
• HTML DOM - standard model for HTML documents
What is the HTML DOM?
• The HTML DOM is a standard object model and programming
interface for HTML. It defines:
• The HTML elements as objects
• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements
• In other words: The HTML DOM is a standard for how to get,
change, add, or delete HTML elements.
JavaScript - HTML DOM Methods
• HTML DOM methods are actions you can perform (on HTML
Elements like add or deleting an HTML element).
• HTML DOM properties are values (of HTML Elements) that you can
set or change(like changing the content of an HTML element).
Example
• The following example changes the content (the innerHTML) of the
<p> element with id="demo":
DOM Selection Methods
• getElementById()
• getElementsByClassName()
• getElementsByTagName()
DOM Selection Methods
getElementById() is a JavaScript DOM method that lets you select a single element on the
web page by its unique id.
What is getElementsByClassName()?
• getElementsByClassName() is a JavaScript DOM method that
lets you select all elements on a web page that share the same
CSS class
• It returns an HTMLCollection (like an array) of all the elements
that match the class name, not just one.
Output
When you
click on button
What is getElementsByClassName()?
• You can also do like this
Output
When you click on button
What is getElementsByClassName()?
• You can also do like this
Output
When you click on button
What is getElementsByClassName()?
• You can also do by using loop
Output
When you click on button
What is getElementsByTagName()?
• getElementsByTagName() is a JavaScript method used to select all
elements on the page with a specific HTML tag name like "p", "div",
"button", etc.
• It returns an HTMLCollection of all matching elements.
Syntax:
document.getElementsByTagName("tag-name");
•"tag-name" is the name of the HTML tag (like "p", "h1", "li", etc.)
•It returns a collection of elements, not just one.
Example
Output
After clicking on Button
DOM Manipulation Methods
• createElement()
• appendChild()
• insertBefore()
• removeChild()
• replaceChild()
createElement() & appendChild()
insertBefore()
parentNode.insertBefore(newNode, referenceNode);
What is removeChild()?
• removeChild() is a method that removes a child element
from its parent node in the DOM.
Syntax:
parentElement.removeChild(childElement)
• parentElement: The element that contains the child you
want to remove.
• childElement: The specific child element you want to
remove.
Example
replaceChild()
• replaceChild() is a DOM method that replaces a child node of a
specified parent with a new node.
Syntax
parentElement.replaceChild(newChild, oldChild);
•parentElement: The parent node that contains the child you want to
replace.
•newChild: The new element that will replace the old one.
•oldChild: The existing child element that will be replaced.
Example
Attribute and Content Manipulation
• element.style (inline styles) is used to modify various types of HTML
elements using JavaScript. This method applies inline styles directly to
elements.
• 1. Change Text Color of a Paragraph
<p id="para">This is a paragraph.</p>
<script>
document.getElementById("para").style.color = "blue";
</script>
Attribute and Content Manipulation
• 2. Change Background Color
<div id="myDiv">Hello, I'm a div!</div>
<script>
document.getElementById("myDiv").style.backgroundColor = "lightgreen";
</script>
3. Change Button Style
<button id="btn">Click Me</button>
<script>
var button = document.getElementById("btn");
button.style.padding = "10px";
button.style.borderRadius = "8px";
button.style.backgroundColor = "orange";
</script>
Attribute and Content Manipulation
• 4. Style an Image
<img id="myImg" src="https://via.placeholder.com/100">
<script>
var img = document.getElementById("myImg");
img.style.border = "2px solid red";
img.style.width = "150px";
img.style.height = "150px";
• </script>
Attribute and Content Manipulation
• 5. Style a Heading
<h1 id="heading">Main Heading</h1>
<script>
document.getElementById("heading").style.fontFamily = "Arial";
document.getElementById("heading").style.color = "purple";
</script>
Attribute and Content Manipulation
• 6. Style a Link
<a id="myLink" href="#">Visit Me</a>
<script>
var link = document.getElementById("myLink");
link.style.textDecoration = "none";
link.style.color = "green";
link.style.fontWeight = "bold";
</script>
Attribute and Content Manipulation
• 7. Style an Ordered List
<ol id="myList">
<li>One</li>
<li>Two</li>
</ol>
<script>
var list = document.getElementById("myList");
list.style.color = "brown";
list.style.fontStyle = "italic";
</script>
Attribute and Content Manipulation
• 8. Style a Table
<table id="myTable" border="1">
<tr><td>Cell 1</td><td>Cell 2</td></tr>
</table>
<script>
var table = document.getElementById("myTable");
table.style.borderCollapse = "collapse";
table.style.backgroundColor = "#f0f0f0";
</script>
Example
Example to change the value of the src attribute of an <img> element
Basic HTML Form with Validation Using JS
Requirements:
• Check if name is not empty
• Check if email contains @
• Show an alert on success or error
Output
Automatic HTML Form Validation(already discussed)
HTML form validation can be performed automatically by the browser:
If a form field (fname) is empty, the required attribute prevents this form from being
submitted:
DOM Events
Mouse Events
• Click(onclick)
• Double click(ondblclick)
• Right click
• Mouse Hover
• Mouse Out
• Mouse Down
• Mouse Up
Keyboard Events
• Key Press
Window Events
• Resize
• Scroll
• Load
Click event(onclick)
Double click(ondblclick)
• When we double click on hello every one paragraph then the hello() will
call
Right click(oncontextmenu)
Mouse hover(onmouseenter)
• When you just mouse hover the text the alert will
generate
Mouse Out(onmouseout)
• The onmouseout events can be used to trigger a function when the user
mouses out of, an HTML element
Mouse Down(onmousedown)
• Similar to click event when we click on element then
function will call
Mouse up(onmouseup)
• when the mouse-button is released, the onmouseup event is triggered
Onkeypress event
• Just work on body or form tag, and when we click on
any key from keyboard then this event will trigger
Onresize event
• Work on body tag, and When you resize the window
then this event will be trigger
Onscroll event
• When you scroll window then this event trigger