TOPIC-3
TOPIC-3
HTML DOM
The HTML DOM (Document Object Model) is a programming interface for web
documents. It defines the structure of an HTML document as a tree of objects, where
each part of the document (elements, attributes, and text) is a node in that tree. The
DOM provides a way to interact with, modify, and manipulate the content, structure,
and style of a webpage using programming languages like JavaScript.
1. Selecting Elements
getElementById()
• The getElementById() method returns null if the element does not exist.
• The getElementById() method is one of the most common methods in the HTML
DOM. It is used almost every time you want to read or edit an HTML element.
Note:
• If two or more elements with the same id exist, getElementById() returns the
first.
Example:
HTML:
<p id="demo">”Hello World”</p>
JS:
document.getElementById("demo").innerHTML = "Hello, John";
getElementsByClassName()
• The getElementsByClassName() method returns a collection of elements with a
specified class name(s).
• The getElementsByClassName() method returns an HTMLCollection.
Example:
HTML:
<div class="example">Element1</div>
<div class="example">Element2</div>
JS:
const collection = document.getElementsByClassName("example");
collection[0].innerHTML = "Hello World!";
getElementsByName()
• The getElementsByName() method returns a collection of elements with a
specified name.
• The getElementsByName() method returns a live NodeList.
Nodelist
• The nodes in the list can be accessed by index. The index starts at 0.
HTML:
<p id="demo"></p>
JS:
document.getElementById("demo").innerHTML = elements[0].tagName;
getElementsByTagName()
• The getElementsByTagName() method returns a collection of all elements with a
specified tag name.
• The getElementsByTagName() method returns an HTMLCollection.
• The getElementsByTagName() property is read-only.
NOTE:
Assignment:
• Create a button for each element selection. Instead of displaying automatically,
use the button to change the display.