wt2021 Handout w05 DOM
wt2021 Handout w05 DOM
2. HTML DOM
3. DOM Programming Interface
What is the DOM?
HTML
<html>
<head>
<title>Sample DOM Document</title>
</head>
<body>
<h1>An HTML Document</h1>
<p>This is a <i>simple</i> document.</p>
</body>
</html>
<html>
<head> <body>
<title>
<h1> <p>
"Sample DOM Document"
"simple"
This is a drawing of the model that the
browser is working with for the page.
Types of DOM nodes
4. Text Node
MP.WEBTECH.IT.KMITL
Document
MP.WEBTECH.IT.KMITL
Root Element:
<html>
Element: Element:
<head> <body>
Properties
Method
Programming Interface
Properties:
MP.WEBTECH.IT.KMITL
<div id="div1">
HTML
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
<p>This is new.</p>
</div>
JavaScript
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
Programming Interface
<div id="div1">
HTML
<p>This is new.</p>
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
HTML
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
JavaScript
var parent = document.getElementById("div1");
var child = document. getElementById ("p1");
parent.removeChild(child);
Programming Interface
HTML
<div id="div1">
<p id="p1">First paragraph</p>
<p id="p2">Second Paragraph</p>
</div>
JavaScript
var newPar = document.createElement("p");
var node = document.createTextNode("This is new.");
newPar.appendChild(node);
var parent = document. getElementById("div1");
var oldPar = document. getElementById("p1");
parent.replaceChild(newPar, oldPar);
Programming Interface
Every element has just one parent. To get it, you can
use Node.parentNode or Node.parentElement.
❑ parentNode returns the parent of the specified
node in the DOM tree.
❑ parentElement returns the DOM node’s parent
Element, or null if the node either has no parent, or
its parent isn’t a DOM Element.
More Information
❑ JavaScript Tutorial
MP.WEBTECH.IT.KMITL
https://www.w3schools.com/js/default.asp
❑ XML DOM Tutorial
https://www.w3schools.com/xml/dom_intro.asp