[1, 2, 5, 6, -1, 8, 11]
In File
In Memory
1
/ \
2 5
/ \ / \
6 -1 8 11
Definitions:
The Document Object Model is a platform- and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure and style of documents. The document can be further processed and the results of that processing can be incorporated back into the presented page. - W3C
<html>
<body>
<p>
Hello World
</p>
<div> <img src="example.png"/></div>
</body>
</html>
The output tree (the "parse tree") is a tree of DOM element and attribute nodes. DOM is short for Document Object Model.
It is the object presentation of the HTML document and the interface of HTML elements to the outside world like JavaScript.
There are more ...
ATTRIBUTE_NODE is not actually part of a tree, but rather is listed for historical reasons.
Be aware that the ATTRIBUTE_NODE is being deprecated in DOM4.
Examples
Object < Node < Element < HTMLElement < (e.g., HTML*Element)
Object < Node < Attr (this is deprecated in DOM4)
Object < Node < CharacterData < Text
Object < Node < Document < HTMLDocument
Object < Node < DocumentFragment
< indicates “inherited from”
document.doctype.nodeName
// "html"
document.doctype
// <!DOCTYPE html>
document.doctype.nodeType
// 10
document.querySelector('a')
// <a ../>
document.querySelector('a').nodeName
// "A"
document.querySelector('a').nodeType
// 1
The document comes with a bunch of methods for selecting elements.
const tag = document.getElementById("highlight");
const tags = document.getElementsByClassName("bolded");
<body>
<h1>Hello</h1>
<h1>Goodbye</h1>
<ul>
<li id="highlight">List Item 1</li>
<li class="bolded">List Item 2</li>
<li class="bolded">List Item 3</li>
</ul>
</body>
document.getElementById()
document.getElementsByClassName()
document.querySelector()
document.getElementsByTagName()
const tags = document.getElementsByTagName("li");
const tags = document.getElementsByTagName("h1");
const tag = document.querySelector(".bolded");
const tags = document.querySelectorAll("h1");
<body>
<h1>Hello</h1>
<h1>Goodbye</h1>
<ul>
<li id="highlight">List Item 1</li>
<li class="bolded">List Item 2</li>
<li class="bolded">List Item 3</li>
</ul>
</body>
document.querySelectorAll()
createElement() and createTextNode()
const elementNode = document.createElement('div');
const textNode = document.createTextNode('Hi');
<!DOCTYPE html>
<html lang="en">
<body>
<div id="A"></div>
<span id="B"></span>
<div id="C"></div>
<div id="D"></div>
<div id="E"></div>
</body>
</html>
//create a strong element and text node and add it to the DOM
document.getElementById('A').innerHTML = '<strong>Hi</strong>';
/* create a div element and text node to replace <span id="B"></div>
(notice span#B is replaced) */
document.getElementById('B').outerHTML = '<div id="B"
class="new">Whats Shaking</div>'
//create a text node and update the div#C with the text node
document.getElementById('C').textContent = 'dude';
//NON standard extensions below i.e., innerText and outerText
//create a text node and update the div#D with the text node
document.getElementById('D').innerText = 'Keep it';
/* create a text node and replace the div#E with the text node
(notice div#E is gone) */
document.getElementById('E').outerText = 'real!'; //non-standard property
console.log(document.body.innerHTML);
/* logs
<div id="A"><strong>Hi</strong></div>
<div id="B" class="new">Whats Shaking</div>
<span id="C">dude</span>
<div id="D">Keep it</div>
real!
*/
appendChild() and insertBefore()
The appendChild() method will append a node (or multiple nodes) to the end of the child node(s) of the node the method is called on.
//create a blink element node and text node
var elementNode = document.createElement('strong');
var textNode = document.createTextNode(' Dude');
//append these nodes to the DOM
document.querySelector('p')
.appendChild(elementNode);
document.querySelector('strong')
.appendChild(textNode);
//log's <p>Hi<strong> Dude</strong></p>
The insertBefore() method requires two parameters: the node to be inserted and the reference node in the document before which you would like the node inserted.
//create a text node and li element
// node and append the text to the li
var text1 = document.createTextNode('1');
var li = document.createElement('li');
li.appendChild(text1);
//select the ul in the document
var ul = document.querySelector('ul');
/*
add the li element we created
above to the DOM, notice I call on <ul>
and pass reference to <li>2</li>
using ul.firstChild
*/
ul.insertBefore(li,ul.firstChild);
console.log(document.body.innerHTML);
/*logs
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
*/
removeChild() and replaceChild()
//remove element node
var divA = document.getElementById('A');
divA.parentNode.removeChild(divA);
//remove text node
var divB = document.getElementById('B').firstChild;
divB.parentNode.removeChild(divB);
<div id="A">Hi</div>
<div id="B">Dude</div>
//set
divStyle.backgroundColor = 'red';
divStyle.border = '1px solid black';
divStyle.width = '100px';
divStyle.height = '100px';
const divStyle = document.querySelector('div').style;
// Remove
divStyle.backgroundColor = '';
divStyle.border = '';
divStyle.width = '';
divStyle.height = '';
//get
console.log(divStyle.backgroundColor);
console.log(divStyle.border);
console.log(divStyle.width);
console.log(divStyle.height);
setProperty(propertyName, value)
removeProperty()
divStyle.setProperty('background-color','red');
divStyle.setProperty('border','1px solid black');
getProperty(propertyName)
divStyle.getPropertyValue('background-color');
divStyle.getPropertyValue('border');
cssText
divStyle.removeProperty('background-color');
divStyle.removeProperty('border');
divStyle.cssText = 'background-color:red;
border:1px solid black;
height:100px;
width:100px;';
getComputedStyle()
To get an element’s CSS from the cascade (i.e., cascading from inline stylesheets, external stylesheets, and browser stylesheets) as well as its inline styles.
Setting up events can be accomplished using
<body onclick="console.log('fire/trigger attribute event handler')">
var elementDiv = document.querySelector('div');
elementDiv.onclick = function() {
console.log('fire/trigger property event handler');
};
elementDiv.addEventListener('click',function() {
console.log('fire/trigger addEventListener')
}, false);
only the addEventListener() provides a robust and organized solution.
inline attribute event handlers
property event handlers
addEventListener() method.
The removeEventListener() method can be used to remove event listeners, if the original listener was not added using an anonymous function
var sayHi = function(){console.log('hi')};
//adding event listener using anonymous function
document.body.addEventListener('click',function(){
console.log('dude');
},false);
document.querySelector('div').removeEventListener('click',sayHi,false);
//adding event listener using function reference
document.querySelector('div').addEventListener('click',sayHi,false);
Anonymous functions added using the addEventListener() method simply cannot be removed.
Event objects are dispatched to an event target. But before dispatch can begin, the event object’s propagation path must first be determined.
Event Object
By default, the handler or callback function invoked for events is sent a parameter that contains all relevant information about the event itself
document.querySelector('div').addEventListener('click', function(event) {
Object.keys(event).sort().forEach(function(item){
console.log(item+' = '+event[item]); //logs event properties and values
});
},false);
preventDefault()
stopPropagation()
<table border="1">
<tbody>
<tr><td>row 1 column 1</td><td>row 1 column 2</td></tr>
<tr><td>row 2 column 1</td><td>row 2 column 2</td></tr>
<tr><td>row 3 column 1</td><td>row 3 column 2</td></tr>
<tr><td>row 4 column 1</td><td>row 4 column 2</td></tr>
<tr><td>row 5 column 1</td><td>row 5 column 2</td></tr>
<tr><td>row 6 column 1</td><td>row 6 column 2</td></tr>
</tbody>
</table>
document.querySelector('table').addEventListener('click', function(event) {
if(event.target.tagName.toLowerCase() === 'td'){
/* make sure we only run code if a td is the target */
console.log(event.target.textContent); /* use event.target to gain access
to target of the event which is
the td */
}
},false);