[go: up one dir, main page]

0% found this document useful (0 votes)
6 views25 pages

Internet Based Programming: Frontend Web Development

The document provides an overview of the HTML Document Object Model (DOM) and its role in frontend web development using JavaScript. It explains how JavaScript can access and manipulate HTML elements, attributes, and styles, as well as handle events and validate forms. Various methods for accessing HTML elements by ID, tag name, class name, and CSS selectors are also detailed, along with examples demonstrating these concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views25 pages

Internet Based Programming: Frontend Web Development

The document provides an overview of the HTML Document Object Model (DOM) and its role in frontend web development using JavaScript. It explains how JavaScript can access and manipulate HTML elements, attributes, and styles, as well as handle events and validate forms. Various methods for accessing HTML elements by ID, tag name, class name, and CSS selectors are also detailed, along with examples demonstrating these concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

05/18/2025

Internet Based Programming


Frontend web development: JS (HTML Document Object Model- HTML DOM: introduction,
methods & properties, document, accessing html elements, changing HTML elements,
changing the value of an attribute, changing CSS, validation, events, eventlistener, adding,
deleting and replacing elements)

Asst. Prof. Dr. İnan KAZANCI


ikazanci@bandirma.edu.tr

Frontend web development- JS: HTML DOM: What is DOM?


• With the HTML Document Object Model (DOM), JavaScript can access and change all the
elements of an HTML document. But what is DOM?
• When a web page is loaded, the browser creates a DOM of the page.
• The HTML DOM model is constructed as a tree of Objects.
• The HTML DOM is a W3C (World Wide Web Consortium) 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.

05/18/2025 2

1
05/18/2025

Frontend web development- JS: HTML DOM: What is DOM?


<html>
<head>
<title>DOM Model</title>
</head>
<body>
<h1>Internet Based Programming</h1>
<p>DOM Tree</p>
<p id="text">This is a text element in the DOM tree.</p>
</body>
</html>

Text:
Internet
Based
Programming

05/18/2025 3

Frontend web development- JS: HTML DOM: What is DOM?

• 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.

05/18/2025 4

2
05/18/2025

Frontend web development- JS: HTML DOM: Methods


& Properties
• The HTML DOM can be accessed with JavaScript.
 In the DOM, all HTML elements are defined as objects.
 The programming interface is the properties and methods of each object.
• HTML DOM methods: are actions you can do (like access, add or deleting an HTML element).
• HTML DOM properties: are values that you can get or set (like changing the content of an HTML
element).
<!DOCTYPE html>
<html>
<body>
<h2>My First Page</h2>
<p id="demo"></p>
In this example, getElementById is
<script> a method, while innerHTML is
document.getElementById("demo").innerHTML = "Hello a property.
World!";
</script>
</body>
</html>

05/18/2025 5

Frontend web development- JS: HTML DOM: Document


• The HTML DOM document object is the owner and representative of all other
objects in the web page.
• If you want to access any element in an HTML page, you always start with
accessing the document object.
• Using document object you can:
Access HTML Elements.
Changing HTML Elements.
Adding and Deleting Elements.
Adding Events.

05/18/2025 6

3
05/18/2025

Frontend web development- JS: HTML DOM: Accessing


HTML Elements
• Bellow are several methods to find and access HTML elements in an HTML page.
Finding HTML elements by id.
Finding HTML elements by tag name.
Finding HTML elements by class name.
Finding HTML elements by CSS selectors.
Finding HTML elements by HTML object collections.

05/18/2025 7

Frontend web development- JS: HTML DOM: Accessing


HTML Elements
 Finding HTML Element by id: The easiest way to find an HTML element in the DOM, is by using
the element id.
 If the element is found, the method will return the element as an object (in element).
 If the element is not found, element will contain null.
<body>
<p id="intro">Finding HTML Elements by Id</p>
<p id="demo"></p>
<script>
const element = document.getElementById("intro");
document.getElementById("demo").innerHTML =
`The text from the intro paragraph is: <b> ${element.innerHTML} </b>`;
window.console.log(element);
</script>
</body>

05/18/2025 8

4
05/18/2025

Frontend web development- JS: HTML DOM: Accessing


HTML Elements
 Finding HTML Elements by Tag Name:
<!DOCTYPE html>
<html>
<body>
<p>Finding HTML Elements by Tag Name.</p>
This example finds <p id="demo"></p>
<script>
all <p> elements: const element = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = `The text in
first paragraph (index 0) is: <b>${element[0].innerHTML}</b>`;
</script>
</body>
</html>

05/18/2025 9

Frontend web development- JS: HTML DOM: Accessing


HTML Elements
 Finding HTML Elements by Tag Name:

<!DOCTYPE html>
<html>
<body>
This example <div id="main">
finds the element <p>Finding HTML Elements by Tag Name</p>
with id="main", <p>This example demonstrates the <b>getElementsByTagName</b> method.</p>
</div>
and then finds <p id="demo"></p>
all <p> elements <script>
const x = document.getElementById("main");
inside "main": const y = x.getElementsByTagName("p");
document.getElementById("demo").innerHTML =
`The first paragraph (index 0) inside "main" is: <b>${y[0].innerHTML}</b>`;
</script>
</body>
</html>

05/18/2025 10

5
05/18/2025

Frontend web development- JS: HTML DOM: Accessing


HTML Elements
 Finding HTML Elements by Class Name: finds all HTML elements with the same class name.

<!DOCTYPE html>
This example returns <html>
<body>
a list of all elements <p class="intro">Finding HTML Elements by Class Name.</p>
with class="intro“: <p class="intro">Hello World!</p>
<p id="demo"></p>
<script>
const x = document.getElementsByClassName("intro");
document.getElementById("demo").innerHTML =
`The first paragraph (index 0) with class="intro" is: <b>${x[0].innerHTML}</b>`;
</script>
</body>
</html>

05/18/2025 11

Frontend web development- JS: HTML DOM: Accessing


HTML Elements
 Finding HTML Elements by CSS Selectors: If you want to find all HTML elements that match a
specified CSS selector (id, class names, types, attributes, values of attributes, etc.), use
the querySelectorAll() method.
<!DOCTYPE html>
<html>
<body>
This example returns a <p class="intro">Finding HTML Elements by CSS Selector</p>
<p class="intro">Hello World!.</p>
list of all elements
<p id="demo"></p>
with class="intro". <script>
const x = document.querySelectorAll(".intro");
document.getElementById("demo").innerHTML =
`The first paragraph (index 0) with class="intro" is: <b>${x[0].innerHTML}</b>`;
</script>
</body>
</html>
</html>

05/18/2025 12

6
05/18/2025

Frontend web development- JS: HTML DOM: Accessing


HTML Elements
 Finding HTML Elements by HTML Object Collections:
<!DOCTYPE html>
<html>
This example finds the form <body>
element with id="frm1", in <form id="frm1" action="/action_page.php">
First name: <input type="text" name="fname" value="Inan"><br>
the forms collection, and Last name: <input type="text" name="lname" value="Kazanci"><br>
displays all element values: <input type="submit" value="Submit">
</form>
<p>These are the values of each element in the form:</p>
<p id="demo"></p>
<script>
const x = document.forms["frm1"]; document.forms[0];
let text = "";
for (let i = 0; i < x.elements.length; i++) {
text += x.elements[i].value + "<br>";}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

05/18/2025 13

Frontend web development- JS: HTML DOM: Accessing


HTML Elements
 Finding HTML Elements by HTML Object Collections: The following are some accessible HTML
objects (and object collections) :
 document.anchors
 document.body
 document.forms
 document.head
 document.images
 document.links
 document.title

05/18/2025 14

7
05/18/2025

Frontend web development- JS: HTML DOM: Changing


HTML Elements
• The HTML DOM allows JavaScript to change the content of HTML elements by using
the innerHTML property.

<!DOCTYPE html>
<html>
<body>
<h1 id="hd1">Old Heading</h1>
<script>
const element = document.getElementById("hd1");
element.innerHTML = "New Heading";
</script>
<p>JavaScript changed "Old Heading" to "New Heading".</p>
</body>
</html>

05/18/2025 15

Frontend web development- JS: HTML DOM: Changing the


Value of an Attribute
• To change the value of an HTML attribute, use this syntax:

document.getElementById(id).attribute = new value

<!DOCTYPE html>
<html>
<body>
<img id="myImage1" src="Pics/googlelogo.png">
<img id="myImage2" src="Pics/googlelogo.png">
<script>
document.getElementById("myImage2").src = "Pics/tree.png";
</script>
</body>
</html>

05/18/2025 16

8
05/18/2025

Frontend web development- JS: HTML DOM: Changing the


Value of an Attribute
• The value of an HTML attribute can also be changed by using the method
setAttribute(“name", value):
<!DOCTYPE html>
<html>
<body>
<p id="main">Computer Science</p>
<input id = "in" type = "text" />
<script>
let x = document.getElementById("main").innerHTML;
document.getElementById("in").setAttribute("value", x);
</script>
</body>
</html>

 To return the value of an attributee we can use:


document.getElementById("in").getAttribute("name");

05/18/2025 17

Frontend web development- JS: HTML DOM: Changing CSS


• To change the style of an HTML element, use this syntax:

document.getElementById(id).style.property = new style


<!DOCTYPE html>
<html>
<body>
<p>Changing the HTML style:</p>
<p id="p1">Hello World!</p>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
document.getElementById("p2").style.fontFamily = "Arial";
document.getElementById("p2").style.fontSize = "larger";
</script>
</body>
</html>

05/18/2025 18

9
05/18/2025

Frontend web development- JS: HTML DOM: Validation


• HTML form validation can be done by JavaScript.
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value; document.forms["myForm"].elements[0].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
return true;}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
<form id ="myForm" action="www.google.com" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>

05/18/2025 19

Frontend web development- JS: HTML DOM: validation


• JavaScript is often used to validate numeric input:
<!DOCTYPE html>
<html>
<body>
<p>Please input a number between 1 and 10:</p>
<input id="numb">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
// Get the value of the input field with id="numb"
let x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
let text;
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
05/18/2025 20

10
05/18/2025

Frontend web development- JS: HTML DOM: Events


• HTML DOM allows JavaScript to react to HTML events.
• A JavaScript can be executed when an event occurs, like when a user clicks on an HTML
element.
• Examples of HTML events:
When a user clicks the mouse.
When a web page has loaded.
When an image has been loaded.
When the mouse moves over an element.
When an input field is changed.
When an HTML form is submitted.
When a user strokes a key.
05/18/2025 21

Frontend web development- JS: HTML DOM: Events


• Examples:
<!DOCTYPE html>
<html>
<body>
<h2>The onclick Attribute</h2>
<h2 id ="hd1" onclick="document.getElementById('hd1').innerHTML='Hello!'">Click on me!</h2>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<h2>The onclick Attribute</h2>
<h2 onclick="this.innerHTML='Hello!'">Click on me!</h2>
</body>
</html>

05/18/2025 22

11
05/18/2025

Frontend web development- JS: HTML DOM: Events


• Examples:
<!DOCTYPE html>
<html>
<body>
<h2>The onclick Attribute</h2>
<h2 onclick="changeText(this)">Click on this text!</h2>
<script>
function changeText(id) {
id.innerHTML = "'Hello!";
}
</script>
</body>
</html>

05/18/2025 23

Frontend web development- JS: HTML DOM: Events: HTML Event


Attributes
• The Onclick event:
<!DOCTYPE html>
<html>
<body>
<h2>The onclick Events</h2>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
document.getElementById("myBtn").onclick = displayDate;
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
</body>
</html>

05/18/2025 24

12
05/18/2025

Frontend web development- JS: HTML DOM: Events: HTML Event


Attributes
• The onload Event:
The onload event is triggered when the user enters the page.

<!DOCTYPE html>
<html>
<body onload="msg()">
<h1>JavaScript HTML Events</h1>
<h2>The onload Attribute</h2>
<script>
function msg() {
alert("Page is loading");
}
</script>
</body>
</html>

05/18/2025 25

Frontend web development- JS: HTML DOM: Events: HTML Event


Attributes
• The oninput Event:
The oninput event is often to some action while the user input data.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The oninput Attribute</h2>
Enter your name: <input type="text" id="fname" oninput="upperCase()">
<script>
function upperCase() {
const x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>

05/18/2025 26

13
05/18/2025

Frontend web development- JS: HTML DOM: Events: HTML Event


Attributes
• The onchange Event:
The onchange event is often used in combination with validation of input fields.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onchange Attribute</h2>
Enter your name: <input type="text" id="fname" onchange="upperCase()">
<script>
function upperCase() {
const x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>

05/18/2025 27

Frontend web development- JS: HTML DOM: Events: HTML Event


Attributes
• The onmouseover and onmouseout Events:
 The onmouseover and onmouseout events can be used to
trigger a function when the user mouses over, or out of, an
HTML element.
<body>
<h1>JavaScript HTML Events</h1>
<div onmouseover="mOver(this)" onmouseout="mOut(this)"
style="background-
color:red;width:120px;height:20px;padding:40px; text-align: center;">
<b>Before onmouseover</b></div>
<script>
function mOver(obj) {
obj.innerHTML = "<b>while onmouseover</b>"
}
function mOut(obj) {
obj.innerHTML = "<b>After onmouseout</b>"
}
</script>
</body>

05/18/2025 28

14
05/18/2025

Frontend web development- JS: HTML DOM: Events: HTML Event


Attributes
• The onmousedown, onmouseup and onclick Events:
The onmousedown, onmouseup, and onclick events are all parts of a mouse-click.
First when a mouse-button is clicked, the onmousedown event is triggered,
Second, when the mouse-button is released, the onmouseup event is triggered.
Finally, when the mouse-click is completed, the onclick event is triggered.

05/18/2025 29

Frontend web development- JS: HTML DOM: Events: HTML Event


Attributes
• The onmousedown, onmouseup and onclick Events:
<body>
<div onmousedown="mDown(this)" onmouseup="mUp(this)" onclick="setTimeout(mClick,3000, this)"
style="background-color:red;width:90px;height:20px;padding:40px;">
Click Me</div>
<script>
function mDown(obj) {
obj.style.backgroundColor = "blue";
obj.innerHTML = "Release Me";
}
function mUp(obj) {
obj.style.backgroundColor = "green";
obj.innerHTML = "Thank You";
}
function mClick(obj) {
obj.style.backgroundColor = "yellow";
obj.innerHTML = "Clicking Complete";
}
</script>
</body>

05/18/2025 30

15
05/18/2025

Frontend web development- JS: HTML DOM: Events: HTML Event


Attributes
• The onkeydown, onkeypress and onkeyup Events: Handle events that occur when a
user presses a key on the keyboard.
<body>
<p>Press a key in the input field:</p>
<input type="text" onkeydown="myFunction1()" onkeypress="setTimeout(myFunction2,3000)"
onkeyup="myFunction3()">
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script>
function myFunction1() {
document.getElementById("demo1").innerHTML = "You pressed a key inside the input field";}
function myFunction2() {
document.getElementById("demo2").innerHTML = "You are pressing a key inside the input field";}
function myFunction3() {
document.getElementById("demo3").innerHTML = "The pressing of a key a is completed";}
</script>
</body

05/18/2025 31

Frontend web development- JS: HTML DOM: EventListener

• In HTML event attributes, we controlled JavaScript from HTML since these attributes are trigging
on HTML elements and causing JavaScript codes to be execute. In EventListener we are doing the
opposite, we are controlling HTML elements by JavaScript addEventListener() method.
• The addEventListener() method attaches an event handler to the specified element.
• Syntax:

element.addEventListener(event, function, useCapture);


 The first parameter is the type of the event (like "click" or "mousedown" or any other HTML
DOM Event.)
 The second parameter is the function we want to call when the event occurs.
 The third parameter is a boolean value specifying whether to use event bubbling or event
capturing. This parameter is optional.

05/18/2025 32

16
05/18/2025

Frontend web development- JS: HTML DOM: EventListener


• Example: Adding an event handler to an element:
<body>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
document.getElementById("myBtn").addEventListener("click", displayDate);
function displayDate() {
document.getElementById("demo").innerHTML = "Computer Science";
}
</script>
</body>

<body>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
document.getElementById("myBtn").addEventListener("click", function () {
document.getElementById("demo").innerHTML = "Computer Science";
});
</script>
</body>
05/18/2025 33

Frontend web development- JS: HTML DOM: EventListener


• Example: Add many event handlers to the same element:
<body>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
var x = document.getElementById("myBtn");
x.addEventListener("mouseover", myFunction1);
x.addEventListener("click", myFunction2);
x.addEventListener("click", myFunction3);
x.addEventListener("mouseout", myFunction4);
function myFunction1() {
document.getElementById("demo").innerHTML = "Moused over!";}
function myFunction2() {
alert("The bottun is clicked!");}
function myFunction3() {
alert("This function also excuted when the bottun is clicked!");}
function myFunction4() {
document.getElementById("demo").innerHTML = "Moused out!";}
</script>
</body>

05/18/2025 34

17
05/18/2025

Frontend web development- JS: HTML DOM: EventListener

• Example: Add an event handler to the window object:

<!DOCTYPE html>
<html>
<body>
<p>Try resizing this browser window to trigger the "resize" event handler.</p>
<p id="demo"></p>
<script>
window.addEventListener("resize", function () {
document.getElementById("demo").innerHTML = `The window size is:
${window.innerWidth} * ${window.innerHeight}`;
});
</script>
</body>
</html>

05/18/2025 35

Frontend web development- JS: HTML DOM: EventListener

• Passing parameters: When passing parameter values, use an "anonymous function" that
calls the specified function with the parameter:
<body>
<p>Click the button to perform a calculation.</p>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
let p1 = 5;
let p2 = 7;
document.getElementById("myBtn").addEventListener("click", function () {
myFunction(p1, p2);
});
function myFunction(a, b) {
document.getElementById("demo").innerHTML = a * b;}
</script>
</body>

05/18/2025 36

18
05/18/2025

Frontend web development- JS: HTML DOM: EventListener

• Event Bubbling or Event Capturing?


 With the addEventListener() method you can specify the propagation type by using the
"useCapture" parameter: element.addEventListener(event, function, useCapture);
 Event propagation is a way of defining the element order when an event occurs. If you have a
<p> element inside a <div> element, and the user clicks on the <p> element, which element's
"click" event should be handled first?
 There are two ways of event propagation in the HTML DOM, bubbling and capturing.
 In bubbling: The inner most element's event is handled first and then the outer.
 In capturing: The outer most element's event is handled first and then the inner.
 The default value is false, which will use the bubbling propagation, when the value is set to
true, the event uses the capturing propagation.

05/18/2025 37

Frontend web development- JS: HTML DOM: EventListener


• The removeEventListener() method: Removes event handlers that have been attached with the
addEventListener() method.
<head>
<style>
#myDIV {
background-color: coral; padding: 10px; color: white; font-size: 20px;}
</style>
</head>
<body>
<h2>JavaScript removeEventListener()</h2>
<div id="myDIV">
<p>Click the button to remove the div's event handler.</p>
<button onclick="removeHandler()" id="myBtn">Remove</button>
</div>
<p id="demo"></p>
<script>
document.getElementById("myDIV").addEventListener("mousemove", myFunction);

function myFunction() {
document.getElementById("demo").innerHTML = Math.random();}
function removeHandler() {
document.getElementById("myDIV").removeEventListener("mousemove", myFunction);}
</script>
</body>
05/18/2025 38

19
05/18/2025

Frontend web development- JS: HTML DOM: DOM Nodes: Adding,


Deleting and Replacing Elements
• Everything in an HTML document is a
node:
The entire document is a document
node.
Every HTML element is an element
node.
The text inside HTML elements are text
nodes.
All comments are comment nodes.

05/18/2025 39

Frontend web development- JS: HTML DOM: DOM Nodes: Adding,


Deleting and Replacing Elements
• The nodes in the node tree have a hierarchical
relationship to each other.
• The terms parent, child, and sibling are used
to describe the relationships:
In a node tree, the top node is called the
root (or root node).
Every node has exactly one parent, except
the root (which has no parent).
A node can have a number of children.
Siblings (brothers or sisters) are nodes with
the same parent.
• With the HTML DOM, all nodes in the node tree can be accessed by JavaScript.
• New nodes can be created, and all nodes can be modified or deleted.

05/18/2025 40

20
05/18/2025

Frontend web development- JS: HTML DOM: DOM Nodes: Adding,


Deleting and Replacing Elements
• Creating New HTML Elements (Nodes):
<body>
<div id="myDIV" style="background-color: coral; padding: 10px; color: white;
font-size: 20px;">
<ul id="uList">
<li>Computer Engineering</li>
<li>Software Engineering</li>
<li>Artificial Intelligence Engineering</li>
</ul>
</div>
<script>
document.getElementById("uList").innerHTML += "<li> IT Engineering </li>";
</script>
</body>

05/18/2025 41

Frontend web development- JS: HTML DOM: DOM Nodes: Adding,


Deleting and Replacing Elements
• createElement() method is an alternative method of innerHTML for adding or creating
new HTML elements.
• What are the Advantages of createElement over innerHTML?
 Preserves existing references to DOM elements when appending elements: createElement() is faster, as
browsers are not required to parse the HTML string and then build a node tree out of it.
 Preserves event handlers attached to any DOM elements: Setting innerHTML will not automatically
reattach event handlers to the new elements it creates, so you would have to keep track of them yourself
and add them manually.
 Could be simpler/faster in some cases: If you are doing lots of additions, it is not efficient to keep
resetting innerHTML because, although faster for simple changes, repeatedly re-parsing and creating
elements would be slower. Additionally, the string manipulation code may be more complicated.

05/18/2025 42

21
05/18/2025

Frontend web development- JS: HTML DOM: DOM Nodes: Adding,


Deleting and Replacing Elements
• To add new element to the HTML DOM using createElement() method you must follow
these steps:
 First: Create the element (element node).
 Second: To add text to the element, we must create a text node.
 Third: Append the text node to the new element.
 Fourth: Append the new element to an existing element in the document.

05/18/2025 43

Frontend web development- JS: HTML DOM: DOM Nodes: Adding,


Deleting and Replacing Elements
• Example: Adding new element using createElement() method:
<body>
<div id="myDIV" style="background-color: coral; padding: 10px; color: white; font-size: 20px;">
<ul id="uList">
<li>Computer Engineering</li>
<li>Software Engineering</li>
<li>Artificial Intelligence Engineering</li>
</ul>
</div>
<script>
let liElement = document.createElement("li");
let textContent = document.createTextNode("IT Engineering");
liElement.appendChild(textContent);
document.getElementById("uList").appendChild(liElement);
</script>
</body>

05/18/2025 44

22
05/18/2025

Frontend web development- JS: HTML DOM: DOM Nodes: Adding,


Deleting and Replacing Elements
• Creating new HTML Elements- insertBefore(): The appendChild() method in the previous
example, appended the new element as the last child of the parent. If you don't want that you
can use the insertBefore() method:
<body>
<div id="myDIV" style="background-color: coral; padding: 10px; color: white; font-size: 20px;">
<ul id="uList">
<li id="li1">Computer Engineering</li>
<li id="li2">Software Engineering</li>
<li id="li3">Artificial Intelligence Engineering</li>
</ul>
</div>
<script>
let liElement = document.createElement("li");
let textContent = document.createTextNode("IT Engineering");
liElement.appendChild(textContent);
let before = document.getElementById("li3")
document.getElementById("uList").insertBefore(liElement, before);
</script>
</body>

05/18/2025 45

Frontend web development- JS: HTML DOM: DOM Nodes: Adding,


Deleting and Replacing Elements
• Removing Existing HTML Elements: To remove an HTML element, use the remove() method:
<body>
<div id="myDIV" style="background-color: coral; padding: 10px; color: white; font-size: 20px;">
<ul id="uList">
<li id="li1">Computer Engineering</li>
<li id="li2">Software Engineering</li>
<li id="li3">Artificial Intelligence Engineering</li>
</ul>
<button onclick="myFunction()">Remove Element</button>
</div>
<script>
function myFunction() {
document.getElementById("li2").remove();}
</script>
</body>

05/18/2025 46

23
05/18/2025

Frontend web development- JS: HTML DOM: DOM Nodes: Adding,


Deleting and Replacing Elements
• Removing a Child Node: It is also possible to remove a child element by finding its parent node
and remove the child element from it.
<body>
<div id="myDIV" style="background-color: coral; padding: 10px; color: white; font-size: 20px;">
<ul id="uList">
<li id="li1">Computer Engineering</li>
<li id="li2">Software Engineering</li>
<li id="li3">Artificial Intelligence Engineering</li>
</ul>
<button onclick="myFunction()">Remove Element</button>
</div>
<script>
function myFunction() {
let parent = document.getElementById("uList");
let child = document.getElementById("li2");
parent.removeChild(child);
}
</script>
</body>

05/18/2025 47

Frontend web development- JS: HTML DOM: DOM Nodes: Adding,


Deleting and Replacing Elements
• Replacing HTML Elements: It is possible to replace an element in the HTML DOM with another element
using the replaceChild() method:
<body>
<div id="myDIV" style="background-color: coral; padding: 10px; color: white; font-size: 20px;">
<ul id="uList">
<li id="li1">Computer Engineering</li>
<li id="li2">Software Engineering</li>
<li id="li3">Artificial Intelligence Engineering</li>
</ul>
<button onclick="myFunction()">Replace Element</button>
</div>
<script>
function myFunction() {
let liElement = document.createElement("li");
let textContent = document.createTextNode("IT Engineering");
liElement.appendChild(textContent);
let parent = document.getElementById("uList");
let toremove = document.getElementById("li2");
parent.replaceChild(liElement, toremove);}
</script>
</body>

05/18/2025 48

24
05/18/2025

Frontend web development- JS: HTML DOM: DOM Nodes: Adding,


Deleting and Replacing Elements
• Replacing HTML Elements: Example2
<body>
<h2>Replace an HTML Element.</h2>
<div id="div1">
<h1 id="hd">This is a paragraph1.</h1>
<p id="p2">This is a paragraph2.</p>
</div>
<script>
const parent = document.getElementById("div1");
const toremove = document.getElementById("hd");
const toadd = document.createElement("p");
const node = document.createTextNode("This is new.");
toadd.appendChild(node);
parent.replaceChild(toadd, toremove);
</script>
</body>

05/18/2025 49

05/18/2025 50

25

You might also like