0% found this document useful (0 votes)
98 views

Javascript HTML Dom Elements

The document discusses the HTML DOM (Document Object Model) and how it allows JavaScript to dynamically access and update elements in an HTML document. It describes how the browser constructs an HTML DOM tree when a web page loads, and how JavaScript can then use the DOM to modify HTML elements, styles, attributes, and content. It provides examples of using different JavaScript DOM methods like getElementById(), getElementsByTagName(), and querySelectorAll() to select elements, and then manipulating their properties.

Uploaded by

Raja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views

Javascript HTML Dom Elements

The document discusses the HTML DOM (Document Object Model) and how it allows JavaScript to dynamically access and update elements in an HTML document. It describes how the browser constructs an HTML DOM tree when a web page loads, and how JavaScript can then use the DOM to modify HTML elements, styles, attributes, and content. It provides examples of using different JavaScript DOM methods like getElementById(), getElementsByTagName(), and querySelectorAll() to select elements, and then manipulating their properties.

Uploaded by

Raja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

The 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:

The HTML DOM Tree of Objects

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

JavaScript HTML DOM


Elements
Finding HTML Elements
DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI) 1
Often, with JavaScript, you want to manipulate HTML elements.

To do so, you have to find the elements first. There are several ways to do
this:

 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

Finding HTML Element by Id


The easiest way to find an HTML element in the DOM, is by using the
element id.

This example finds the element with id="intro":

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM</h2>

<p id="intro">Finding HTML Elements by Id</p>


<p>This example demonstrates the <b>getElementsById</b> method.</p>

<p id="demo"></p>

<script>
const element = document.getElementById("intro");

document.getElementById("demo").innerHTML =
"The text from the intro paragraph is: " + element.innerHTML;

</script>

</body>
</html>

DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI) 2


Finding HTML Elements by Tag Name
This example finds all <p> elements:

<html>
<body>

<h2>JavaScript HTML DOM</h2>

<p>Finding HTML Elements by Tag Name.</p>


<p>This example demonstrates the <b>getElementsByTagName</b>
method.</p>

<p id="demo"></p>

<script>
const element = document.getElementsByTagName("p");

document.getElementById("demo").innerHTML = 'The text in first paragraph


(index 0) is: ' + element[0].innerHTML;

</script>

</body>
</html>

Finding HTML Elements by Class Name


If you want to find all HTML elements with the same class name,
use getElementsByClassName().

This example returns a list of all elements with class="intro".

<html>
<body>

<h2>JavaScript HTML DOM</h2>

<p>Finding HTML Elements by Class Name.</p>


<p class="intro">Hello World!</p>
<p class="intro">This example demonstrates the
<b>getElementsByClassName</b> method.</p>
DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI) 3
<p id="demo"></p>

<script>
const x = document.getElementsByClassName("intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with class="intro" is: ' + x[0].innerHTML;
</script>

</body>
</html>

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.

This example returns a list of all <p> elements with class="intro".

<html>
<body>

<h2>JavaScript HTML DOM</h2>

<p>Finding HTML Elements by Query Selector</p>


<p class="intro">Hello World!.</p>
<p class="intro">This example demonstrates the <b>querySelectorAll</b>
method.</p>

<p id="demo"></p>

<script>
const x = document.querySelectorAll("p.intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with class="intro" is: ' + x[0].innerHTML;
</script>

</body>
</html>

DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI) 4


Finding HTML Elements by HTML Object
Collections
This example finds the form element with id="frm1", in the forms collection,
and displays all element values:

<html>
<body>

<h2>JavaScript HTML DOM</h2>


<p>Finding HTML Elements Using <b>document.forms</b>.</p>

<form id="frm1" action="/action_page.php">


First name: <input type="text" name="fname" value="Donald"><br>
Last name: <input type="text" name="lname" value="Duck"><br><br>
<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"];
let text = "";
for (let i = 0; i < x.length ;i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Finding HTML Elements Using document.anchors


<html>
<body>

<h2>Finding HTML Elements Using document.anchors</h2>

DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI) 5


<a name="html">HTML Tutorial</a><br>
<a name="css">CSS Tutorial</a><br>
<a name="xml">XML Tutorial</a><br>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"Number of anchors are: " + document.anchors.length;
</script>

</body>
</html>

// Body Content

<html>
<body>

<h2>JavaScript HTMLDOM</h2>
<p>Displaying document.body</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = document.body.innerHTML;
</script>

</body>
</html>

//documentElement

<html>
<body>

<h2>JavaScript HTMLDOM</h2>
<p>Displaying document.documentElement</p>

<p id="demo"></p>

DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI) 6


<script>
document.getElementById("demo").innerHTML =
document.documentElement.innerHTML;
</script>

</body>
</html>

//Embed

<html>
<body>

<h2>JavaScript HTMLDOM</h2>
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"Number of embeds: " + document.embeds.length;
</script>

</body>
</html>

Finding HTML Elements Using document.forms


<html>
<body>

<h2>Finding HTML Elements Using document.forms</h2>

<form action="">
First name: <input type="text" name="fname" value="Donald">
<input type="submit" value="Submit">
</form>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"Number of forms: " + document.forms.length;
</script>

DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI) 7


</body>
</html>

//Document Head

<html>

<head>
<title>W3Schools Demo</title>
</head>

<body>

<h2>JavaScript HTMLDOM</h2>
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
document.head;
</script>

</body>
</html>

Finding HTML Elements Using document.images


<html>
<body>

<h2>Finding HTML Elements Using document.images</h2>

<img src="pic_htmltree.gif" width="486" height="266">


<img src="pic_navigate.gif" width="362" height="255">

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"Number of images: " + document.images.length;
</script>

DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI) 8


</body>
</html>

Finding HTML Elements Using document.links


<html>
<body>

<h2>Finding HTML Elements Using document.links</h2>

<p>
<a href="/html/default.asp">HTML</a>
<br>
<a href="/css/default.asp">CSS</a>
</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"Number of links: " + document.links.length;
</script>

</body>
</html>

Finding HTML Elements Using document.scripts


<html>
<body>

<h2>Finding HTML Elements Using document.scripts</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"Number of scripts: " + document.scripts.length;
</script>

DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI) 9


</body>
</html>

Finding HTML Elements Using document.title


<html>
<head>
<title>Deepak Demo</title>
</head>
<body>

<h2>Finding HTML Elements Using document.title</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"The title of this document is: " + document.title;
</script>

</body>
</html>

JavaScript HTML DOM -


Changing CSS
The HTML DOM allows JavaScript to change the style of HTML elements.

Changing HTML Style


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

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

1
DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI)
0
The following example changes the style of a <p> element:

<html>
<body>

<h2>JavaScript HTML DOM</h2>


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

Using Events
The HTML DOM allows you to execute code when an event occurs.

Events are generated by the browser when "things happen" to HTML


elements:

 An element is clicked on
 The page has loaded
 Input fields are changed

You will learn more about events in the next chapter of this tutorial.

This example changes the style of the HTML element with id="id1", when the
user clicks a button

<html>
<body>

<h1 id="id1">My Heading 1</h1>

1
DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI)
1
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>

</body>
</html>

JavaScript HTML DOM


Animation
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
<body>

<p><button onclick="myMove()">Click Me</button></p>

<div id ="container">
<div id ="animate"></div>
</div>

<script>
function myMove() {
let id = null;
const elem = document.getElementById("animate");
1
DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI)
2
let pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
</script>

</body>
</html>

JavaScript HTML DOM Events


In this example, the content of the <h1> element is changed when a user
clicks on it:

<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>

<h2 onclick="this.innerHTML='Ooops!'">Click on this text!</h2>

</body>
</html>

In this example, a function is called from the event handler:

<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>

<h2 onclick="changeText(this)">Click on this text!</h2>

1
DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI)
3
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>

</body>
</html>

To assign events to HTML elements you can use event attributes.

<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>

<p>Click the button to display the date.</p>


<button onclick="displayDate()">The time is?</button>

<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>

<p id="demo"></p>

</body>
</html>

Assign Events Using the HTML DOM


<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Events</h2>

<p>Click "Try it" to execute the displayDate() function.</p>


<button id="myBtn">Try it</button>

<p id="demo"></p>
1
DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI)
4
<script>
document.getElementById("myBtn").onclick = displayDate;

function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>

</body>
</html>

The onload and onunload Events


The onload and onunload events are triggered when the user enters or leaves
the page.

The onload event can be used to check the visitor's browser type and browser
version, and load the proper version of the web page based on the
information.

The onload and onunload events can be used to deal with cookies.

<html>
<body onload="checkCookies()">

<h1>JavaScript HTML Events</h1>


<h2>The onload Attribute</h2>

<p id="demo"></p>

<script>
function checkCookies() {
let text = "";
if (navigator.cookieEnabled == true) {
text = "Cookies are enabled.";
} else {
text = "Cookies are not enabled.";
}
document.getElementById("demo").innerHTML = text;
}
</script>

1
DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI)
5
</body>
</html>

The oninput Event


The oninput event is often to to some action while the user input data.

Below is an example of how to use the oninput to change the content of an


input field.

<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The oninput Attribute</h2>

Enter your name: <input type="text" id="fname" oninput="upperCase()">


<p>When you write in the input field, a function is triggered to transform the
input to upper case.</p>

<script>
function upperCase() {
const x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>

</body>
</html>

The onchange Event


The onchange event is often used in combination with validation of input fields.

Below is an example of how to use the onchange. The upperCase() function will
be called when a user changes the content of an input field.

<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onchange Attribute</h2>
1
DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI)
6
Enter your name: <input type="text" id="fname" onchange="upperCase()">
<p>When you leave the input field, a function transforms the input to upper
case.</p>

<script>
function upperCase() {
const x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>

</body>
</html>

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:

<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onmouseover Attribute</h2>

<div onmouseover="mOver(this)" onmouseout="mOut(this)"


style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
Mouse Over Me</div>

<script>
function mOver(obj) {
obj.innerHTML = "Thank You"
}

function mOut(obj) {
obj.innerHTML = "Mouse Over Me"
}
</script>

1
DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI)
7
</body>
</html>

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,
then, when the mouse-button is released, the onmouseup event is triggered,
finally, when the mouse-click is completed, the onclick event is triggered.

Thank You

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onmousedown Attribute</h2>

<div onmousedown="mDown(this)" onmouseup="mUp(this)"


style="background-color:#D94A38;width:90px;height:20px;padding:40px;">
Click Me</div>

<script>
function mDown(obj) {
obj.style.backgroundColor = "#1ec5e5";
obj.innerHTML = "Release Me";
}

function mUp(obj) {
obj.style.backgroundColor="#D94A38";
obj.innerHTML="Thank You";
}
</script>

</body>
</html>

1
DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI)
8
JavaScript HTML Events

The onfocus Attribute


<html>
<head>
<script>
function myFunction(x) {
x.style.background = "yellow";
}
</script>
</head>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onfocus Attribute</h2>

Enter your name: <input type="text" onfocus="myFunction(this)">

<p>When the input field gets focus, a function is triggered which changes the
background-color.</p>

</body>
</html>

// Mouse over

<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onmousover Attribute</h2>

<h1 onmouseover="style.color='red'"
onmouseout="style.color='black'">
Mouse over this text</h1>

</body>
</html>

1
DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI)
9
JavaScript HTML DOM
EventListener
<html>
<body>

<h2>JavaScript addEventListener()</h2>

<p>This example uses the addEventListener() method to attach a click event to


a button.</p>

<button id="myBtn">Try it</button>

<p id="demo"></p>

<script>
document.getElementById("myBtn").addEventListener("click", displayDate);

function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>

</body>
</html>

Add Many Event Handlers to the Same


Element
The addEventListener() method allows you to add many events to the same
element, without overwriting existing events:

<html>
<body>

<h2>JavaScript addEventListener()</h2>

2
DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI)
0
<p>This example uses the addEventListener() method to add two click events
to the same button.</p>

<button id="myBtn">Try it</button>

<script>
var x = document.getElementById("myBtn");
x.addEventListener("click", myFunction);
x.addEventListener("click", someOtherFunction);

function myFunction() {
alert ("Hello World!");
}

function someOtherFunction() {
alert ("This function was also executed!");
}
</script>

</body>
</html>

Add an Event Handler to the window


Object
The addEventListener() method allows you to add event listeners on any HTML
DOM object such as HTML elements, the HTML document, the window object,
or other objects that support events, like the xmlHttpRequest object

<html>
<body>

<h2>JavaScript addEventListener()</h2>

<p>This example uses the addEventListener() method on the window


object.</p>

<p>Try resizing this browser window to trigger the "resize" event handler.</p>

<p id="demo"></p>

2
DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI)
1
<script>
window.addEventListener("resize", function(){
document.getElementById("demo").innerHTML = Math.random();
});
</script>

</body>
</html>

The removeEventListener() method


The removeEventListener() method removes event handlers that have been
attached with the addEventListener() method:

<html>
<head>
<style>
#myDIV {
background-color: coral;
border: 1px solid;
padding: 50px;
color: white;
font-size: 20px;
}
</style>
</head>
<body>

<h2>JavaScript removeEventListener()</h2>

<div id="myDIV">
<p>This div element has an onmousemove event handler that displays a
random number every time you move your mouse inside this orange field.</p>
<p>Click the button to remove the div's event handler.</p>
<button onclick="removeHandler()" id="myBtn">Remove</button>
</div>

<p id="demo"></p>
2
DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI)
2
<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>
</html>

Creating New HTML Elements (Nodes)


<html>
<body>

<h2>JavaScript HTML DOM</h2>


<p>Add a new HTML Element.</p>

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);
const element = document.getElementById("div1");
element.appendChild(para);
</script>

</body>

2
DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI)
3
</html>

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:

<html>
<body>

<h2>JavaScript HTML DOM</h2>


<p>Add a new HTML Element.</p>

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);

const element = document.getElementById("div1");


const child = document.getElementById("p1");
element.insertBefore(para,child);
</script>

</body>
</html>

Removing Existing HTML Elements


To remove an HTML element, use the remove() method:

2
DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI)
4
<html>
<body>

<h2>JavaScript HTML DOM</h2>


<h3>Remove an HTML Element.</h3>

<div>
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<button onclick="myFunction()">Remove Element</button>

<script>
function myFunction() {
document.getElementById("p1").remove();
}
</script>

</body>
</html>

Removing a Child Node


For browsers that does not support the remove() method, you have to find the
parent node to remove an element:

<html>
<body>

<h2>JavaScript HTML DOM</h2>


<p>Remove Child Element</p>

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
const parent = document.getElementById("div1");
const child = document.getElementById("p1");

2
DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI)
5
parent.removeChild(child);
</script>

</body>
</html>

Replacing HTML Elements


To replace an element to the HTML DOM, use the replaceChild() method:

<html>
<body>

<h2>JavaScript HTML DOM</h2>


<h3>Replace an HTML Element.</h3>

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is a paragraph.</p>
</div>

<script>
const parent = document.getElementById("div1");
const child = document.getElementById("p1");
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);
parent.replaceChild(para,child);
</script>

</body>
</html>

2
DEEPAK SINGH(ASST. PROFESSOR ,MAHADEV P.G. COLLEGE VARANASI)
6

You might also like