Duration: 8 minutes
The DOM (or Document Object Model) is a tree-like representation of the contents of a webpage – a tree of "nodes" with different relationships depending on how they’re arranged in the HTML document.
<div id="wrapper"> <div class="main"></div> <div class="secondary"></div> </div>
In the above example, the
<div class="main"></div> is a "child" of
<div id="wrapper"></div> and a sibling to
<div class="secondary"></div>. Think of it like a family tree.
<div id="wrapper"></div> is a parent, with its children on the next level, each on their own "branch".
If we want to target a specific node that we want to work with then we use the
selectors. These selectors can be a combination of CSS-style selectors and relationship properties.
We will start with the CSS-style selectors. If we want to target the
<div class="main"></div> node then we could use the following selectors:
In addition we can use relational selectors (i.e.
lastElementChild etc.) with special properties owned by the nodes.
const wrapper = document.querySelector('#wrapper'); // select the #wrapper div (don't worry about the syntax, we'll get there) console.dir(wrapper.firstElementChild); // select the first child of #wrapper => .main const secondary = document.querySelector('.secondary'); // select the .secondary div console.dir(secondary.previousElementSibling); // selects the prior sibling => .main
Basically in the examples above we identifying a certain node based on its relationship to the other nodes around it.
We will start with the
query selectors and those selectors help us to
*There are several other, more specific queries, that offer potential (marginal) performance benefits, but we won’t be going over them now.
Important note: When using querySelectorAll, the return value is not an array. Although it might look an array it somewhat acts like an array, but it’s really a "nodelist". The big difference is that several array methods are missing from nodelists. One solution is to convert the nodelist into an array. You can do this with Array.from() or the spread operator.
[options]in this case means you can add some optional parameters to the function.
const div = document.createElement('div');
Keep in mind that this function does NOT put your new element into the DOM – it simply creates it in memory. Thus before you place the element to the DOM you can add styles, classes, ids, text etc.
Then you can add that element to the DOM with the following methods.
We can also alter the element’s own properties. In other words when we have a reference to an element we can use that reference and do many alterations to the element itself, such as add or remove an attribute, change classes, adding styles and much more.
Let’s see an example. First we will create a div element.
const div = document.createElement('div'); // create a new div referenced in the variable 'div'
In the following sections we will use that div to do several alterations to it.
Now we will add the color purple and the background color gray in to our previously created div.
div.style.color = 'purple'; // adds the indicated style rule div.style.cssText = 'color: purple; background: gray'; // adds several style rules div.setAttribute('style', 'color: purple; background: gray'); // adds several style rules
For further information on inline styles see the DOM Enlightenment’s section on CSS Style rules.
Please be aware that if you’re accessing a kebab-cased css rule from JS, you’ll either need to use camelcase or you’ll need to use bracket notation instead of dot notation.
div.style.background-color // doesn't work - attempts to subtract color from div.style.background div.style.backgroundColor // accesses the divs background-color style div.style['background-color'] // also works div.style.cssText = "background-color: white" // ok in a string
Now let’s see how we can edit an attribute of an element.
div.setAttribute('id', 'myDiv'); // if id exists update it to 'myDiv' else create an id // with value "myDiv" div.getAttribute('id'); // returns value of specified attribute, in this case // "myDiv" div.removeAttribute('id'); // removes specified attribute
For further information on available attributes see MDNs section on HTML Attributes.
Now we will see some examples of methods we use with the class that our element might has.
div.classList.add('content'); // adds class "content" to our new div div.classList.remove('content'); // remove "content" class from div div.classList.toggle('active'); // if div doesn't have class "active" then add it, or if // it does, then remove it
It is often standard (and more clean) to toggle a CSS style rather than adding and removing inline CSS.
Now we will see how we add text content to our element.
div.textContent = 'My first content!' // creates a text node containing "Hello World!" and // inserts it in div
Now we will see how we add HTML content to our element.
div.innerHTML = '<span>My first content!</span>'; // renders the html inside div
*Note that textContent is preferable for adding text, and innerHTML should be used sparingly as it can create security risks if misused. For further information about this topic you can check this article.
Now let’s see an example as a review of what we have covered so far. So in the example we will create a DOM element and we will append it to a webpage.
<!-- HTML FILE --> <body> <h1> HERE IS THE TITLE OF YOUR WEBPAGE </h1> <div id="wrapper"></div> </body>
First we get a reference to the
wrapper div that already exists in our HTML. Then we create a new div and store it in the variable
container. We add a class and some text to the
container div and finally append that div to
<!-- DOM --> <body> <h1> HERE IS THE TITLE OF YOUR WEBPAGE </h1> <div id="wrapper"> <div class="content"> This is our text-content! </div> </div> </body>
In this section you can find a lot of helpful links to other content. This is a supplemental material for you if you want to dive deeper into some concepts.
This W3Schools article offers simple and easy-to-understand lessons on DOM.
JS DOM Crash Course is an extensive and well explained 4 part video series on the DOM by Traversy Media.
Understanding The Dom is an aptly named article-based tutorial series by Digital Ocean.