The Document Object
Model
What is DOM?
The Document Object Model (DOM) is a cross-platform and
language-independent application programming interface.
(API)
The DOM, is the API through which JavaScript interacts
with content within a website.
The DOM API is used to access, traverse and manipulate
HTML and XML documents.
The DOM is a W3C (World Wide Web Consortium)
standard.
HTML DOM Tree Objects
DOM Methods
getElementById()
Accesses any element on the page via its ID attribute • A
fundamental method within the DOM for accessing elements on the
page •
This method will returns single element innerHTML •
The innerHTML is used to get and replace the content of HTML
elements.
DOM Element
Element by class name
Elements by CSS Selectors
Exercise
Write a JavaScript program to modify the text-align, font-size, font-
family of heading1 using getElementById •
Write a JavaScript program to change the background color of all
the tag •
Write a JavaScript to add the text shadow in all paragraphs in the
given essay
DOM Nodes
In the context of DOM, every entity in an HTML or XML document, is referred as a
Node
In JavaScript, all the Nodes are represented as Objects. They have their own
properties and methods
is DocumentType Node is an Element Node, so are meta, title, body, h1, p, ul and
li
Text contents like the title text 'This is a simple HTML document' is a text Node
Some of the Nodes may have children. Like
has
as children • Body has
as children
DOM Node – Tree representation - Revisit
Navigation between nodes
Adding and Deleting Element
DOM Node - Methods
DOM Animation
<p>One</p>
<p>Two</p>
<p>Three</p>
<script>
let paragraphs = document.body.getElementsByTagName("p");
document.body.insertBefore(paragraphs[2], paragraphs[0]);
</script>
Creating nodes
Say we want to write a script that replaces all images (<img> tags) in the document
with the text held in their alt attributes, which specifies an alternative textual
representation of the image.
This involves not only removing the images but adding a new text node
to replace them. Text nodes are created with the document.createTextNode method.
// Given:
<div>
<span id="childSpan">foo bar</span>
</div>
// Create an empty element node
// without an ID, any attributes, or any content
var sp1 = document.createElement("span");
// Give it an id attribute called 'newSpan'
sp1.id = "newSpan";
// Create some content for the new element.
var sp1_content = document.createTextNode("new replacement span element.");
// Apply that content to the new element
sp1.appendChild(sp1_content);
// Build a reference to the existing node to be replaced
var sp2 = document.getElementById("childSpan");
var parentDiv = sp2.parentNode;
// Replace existing node sp2 with the new span element sp1
parentDiv.replaceChild(sp1, sp2);
// Result:
<div>
<span id="newSpan">new replacement span element.</span>
</div>
Attributes
Some element attributes, such as href for links, can be accessed through a property of
the same name on the element’s DOM object. This is the case for most commonly
used standard attributes.
But HTML allows you to set any attribute you want on nodes. This can be useful
because it allows you to store extra information in a document. If you make up your
own attribute names, though, such attributes will not be present as properties on the
element’s node. Instead, you have to use the getAttribute and setAttribute methods
to work with them.
<p data-classified="secret">The launch code is 00000000.</p>
<p data-classified="unclassified">I have two feet.</p>
<script>
let paras = document.body.getElementsByTagName("p");
for (let para of Array.from(paras)) {
if (para.getAttribute("data-classified") == "secret") {
para.remove();
}
}
</script>
Styling
<p id="para" style="color: purple">
Nice text
</p>
<script>
let para = document.getElementById("para");
para.style.color = "magenta";
paragraph.style.background = "#875673";
paragraph.style.fontFamily = "Poppins";
</script>
Query selectors
The querySelectorAll method, which is defined both on the document object and on
element nodes, takes a selector string and returns a NodeList containing all the
elements that it matches.
<p>And if you go chasing
<span class="animal">rabbits</span></p>
<p>And you know you're going to fall</p>
<p>Tell 'em a <span class="character">hookah smoking
<span class="animal">caterpillar</span></span></p>
<p>Has given you the call</p>
<script>
function count(selector) {
return document.querySelectorAll(selector).length;
}
console.log(count("p")); // All <p> elements
// → 4
console.log(count(".animal")); // Class animal
// → 2
console.log(count("p .animal")); // Animal inside of <p>
// → 2
console.log(count("p > .animal")); // Direct child of <p>
// → 1
</script>
querySelector
The querySelector method (without the All part) works in a similar way.
This one is useful if you want a specific, single element. It will return only the
first matching element or null when no element matches.
You can use # Hash symbol to select by Id and . Dot for the class similarly the
tagname you can get By it’s Tag .
The following example we will Select all of them.
<p>And if you go chasing
<span class="animal">rabbits</span></p>
<p>And you know you're going to fall</p>
<p>Tell 'em a <span id="character">hookah smoking
<span class="animal">caterpillar</span></span></p>
<p>Has given you the call</p>
<script>
let byclass = document.querySelector(".animal");
let byId = document.querySelector("#character");
let byTagName = document.querySelector("p");
byclass.style.color = '#8DE3BC';
byId.style.background = "#000";
byTagName.style.background = "#000232"
</script>
End