DOM manipulation
Document Object Model, or DOM for short, is a browser tool, that gives developer access to the page elements (to add new, modify and delete them). DOM represents all page content as objects that can be modified.
Every HTML tag is an object. The text inside a tag is an object as well.
The document object (and a DOM node) that represents the whole document.
Even the <!DOCTYPE...> directive at the very beginning of HTML and all code comments are also a DOM nodes.
Document is an entry point to DOM. Remember: In the DOM, the null value means “doesn’t exist” or doesn't rendered yet.
DOM nodes
Each DOM node belongs to the corresponding built-in class.
- EventTarget – is the root “abstract” class.
- Node – is also an “abstract” class, serving as a base for DOM nodes. It provides the core tree functionality: parentNode, nextSibling, childNodes
- Element – is a base class for DOM elements. It provides element-level navigation like nextElementSibling, children and searching methods like getElementsByTagName, querySelector.
- HTMLElement – is finally the basic class for all HTML elements.
Main DOM node properties are:
- nodeType (1-for element nodes, 3 for text nodes, etc.)
- nodeName/tagName
- innerHTML can be overwritten
elem.innerHTML+="more html" - outerHTML !! writing to outerHTML does not change the element, but it inserts new comntent inside document.
- nodeValue/data
- textContent
- hidden When set to true, does the same as CSS display:none.
HTML attributes (id, text, value, class, style, etc.) also can be found and changed while manipulating with DOM elements by using the following functions:
- elem.hasAttribute(name)
- elem.getAttribute(name)
- elem.setAttribute(name, value)
- elem.removeAttribute(name)
- elem.attributes
Navigation properties: ways to "walk" through the DOM nodes.
document.documentElement --> <html>
document.body --> <body>
document.head --> <head>
For all nodes (text nodes, element nodes, and even comment nodes if they exist.
- elem.parentNode
- elem.childNodes , elem.firstChild , elem.lastChild
- elem.previousSibling , elem.nextSibling
In most cases we need only element nodes, so to manipulate with elements only use the following navigation links:
- elem.parentElement
- elem.children , elem.firstElementChild , elem.lastElementChild
- elem.previousElementSibling , elem.nextElementSibling
ChildNodes and children are not arrays, it's a collection of elements. To iterate through elements, use for ... of, and create a "real array"
if need to use array functions (e.g. Array.from(elem.children).filter)
Navigation functions: searching through document
- elem.querySelector(css)
- elem.querySelectorAll(css)
- document.getElementById(id)
- document.getElementsByName(name)
- elem.getElementsByTagName(tag)
- elem.getElementsByClassName(className)
- elem.closest(css)
Modifying the document
To create new nodes:
document.createElement(tag) // creates an element with the given tag
document.createTextNode(value)// creates a text node (rarely used)
elem.cloneNode(deep) // clones the element
//if deep==true then with all descendants
To insert or remove nodes:
node.append(...nodes or strings) // insert into node, at the end
node.prepend(...nodes or strings) // insert into node, at the beginning
node.before(...nodes or strings) // insert right before node
node.after(...nodes or strings) // insert right after node
node.replaceWith(...nodes or strings)// replace node
node.remove() // remove the node
div.before(document.createElement('hr'), 'some text');
To insert HTML:
elem.insertAdjacentHTML(where, html)
// inserts it depending on the value of where:
// "beforebegin" – insert html right before elem
// "afterbegin" – insert html into elem, at the beginning
// "beforeend" – insert html into elem, at the end
// "afterend" – insert html right after elem
div.insertAdjacentHTML('beforebegin', '<p>Hello</p>');
DocumentFragment is a special DOM node that serves as a wrapper to pass around lists of nodes. E.g.:
function getListContent() {
let fragment = new DocumentFragment();
for(let i=1; i<=3; i++) {
let li = document.createElement('li');
li.append(i);
fragment.append(li);
}
return fragment;
}
ul.append(getListContent());
Finding HTML objects
| Property | Description |
|---|---|
| document.anchors | Returns all <a> elements that have a name attribute |
| document.baseURI | Returns the absolute base URI of the document |
| document.cookie | Returns the document's cookie |
| document.documentElement | Returns the <html> element |
| document.domain | Returns the domain name of the document server |
| document.embeds | Returns all <embed> elements |
| document.forms | Returns all <form> elements |
| document.readyState | Returns the (loading) status of the document |
| document.scripts | Returns all <script> elements |
| document.strictErrorChecking | Returns if error checking is enforced |
| document.URL | Returns the complete URL of the document |
Find more about DOM manipulation here