I am creating this post as notes from Wes Bos Javascript course which you can sign up for and do with me here: https://beginnerjavascript.com/. Here is a link to Wes' GitHub readme.md.
What Is the DOM?
The DOM, if you aren't familiar is how we manipulate HTML and CSS using Javascript. It truly unlocks the power of what Javascript and it's various flavors can unleash. Every browser with inspect tools allows you to view the DOM like you can see above. This is how the browser understands how a webpage looks/acts. It is not a visual representation of what you see in the browser window but more of a tree of objects and their properties.
Javascript Rendering
The way browsers handle Javascript is that it will load the entire script, top-to-bottom before moving to the next line of HTML. This is key when determining when/where to call your Javascript within the HTML. If you call it in the head to manipulate something in the body, well the body hasn't loaded just yet so that script will likely run, error, and then the rest of the HTML document continues to load. It's typically a best practice to add the javascript that manipulates the DOM to the bottom of the body tag below any dependencies of your javascript file.
Examples of dependancies are jQuery & popper.js for bootstrap which if called after the script tag in your html, it will not work correctly. A work around to this is to add an argument that includes something like this:
document.addEventListener('DOMContentLoaded', someFunctionOrVariable);
which will allow the full DOM to run before that DOM manipulation argument via a callback/promise - but we are getting way ahead of ourselves here.
How to Manipulate the DOM
document
is the object to focus on when referring to DOM manipulation. The document
object allows you to create, edit, remove HTML/CSS. In order to manipulate anything on the DOM, you will need to follow a specific process of "Selecting" first then manipulating it's properties or methods.
Selecting
It used to be that Javascript's DOM tree was kind of broken but recent updates with Javascript, specifically with the method querySelector
and querySelectorAll
you can select parts of the HTML exactly as you would within CSS. For example for a <p>
tag, you can select it by creating a constant like so:
const p = document.querySelector('p');
const p = document.querySelectorAll('p');
and this can but done for any selector like you normally would with CSS. For example .container
#myId
or div
.
Another cool thing you can do is to create a const as a method of a current querySelector. Here is what I mean:
const ul = document.querySelector('ul'); const li = ul.querySelectorAll('li')
What this will allow you to do is to select all the li
tags within the first ul
on the DOM (obviously an li
tag would live inside of a ul
but this was just a cheap example).
The old way to do this was to use some of these, while it's useful it isn't really necessary to learn anymore but definitely good to know it exists for reference. You can see a whole list here:
https://developer.mozilla.org/en-US/docs/Web/API/DocumentgetAnimations()
getBoxObjectFor()
getElementById()
getElementsByClassName()
getElementsByName()
getElementsByTagName()
getElementsByTagNameNS()
The above will call the first p tag and only the first one it finds from the top of the DOM. If you wanted to select all paragraph tags, you'd do almost the exact same line of code like so:
Misc Note: The global scope on the browser is the
window
- any global variables you create can actually be called on the window as a method of the window. For exampleconst myGlobalVariable = 'things';
window.myGlobalVariable === myGlobalVariable
would result intrue
.
Ok, You Selected It, Now What?
This is intended to just be a shortlist of some really useful methods of DOM manipulation. Review https://developer.mozilla.org/en-US/docs/Web/API/Element and https://developer.mozilla.org/en-US/docs/Web/API/Node for more possibilities.
Before we do anything with it, let's learn about Element Properties and Methods
const header = document.querySelector('h1');
In the example above, we aren't doing anything with it. We just selected it. So how do you manipulate it?
One way is to use predefined methods. Let's explore some:
innerText and textContent
const header = document.querySelector('h1'); header.textContent = 'Drew Learned: How to edit an H1 using querySelector!';
If you opened up the browser console on this page and ran the above script, you'd update the title of this post to "Drew Learned: How to edit an H1 using querySelector!". Let's consider a few more examples.
Note:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerTextinnerText
is easily confused withNode.textContent
, but there are important differences between the two. Basically,innerText
is aware of the rendered appearance of text, whiletextContent
is not.
See the Pen innerText Vs innerHTML by Drew (@DrewLearns) on CodePen.
insertAdjacentText();
insertAdjacentText();
is another noteworthy method to use. I'd strongly recommend reviewing https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentText along with this post for more details.
See the Pen Jjormmm by Drew (@DrewLearns) on CodePen.
To be continued...
If you would like to learn more, check out part 2 of this blog series: https://codingwithdrew.com/2020/01/02/manipulating-the-document-object-model-part-2/
Drew is a seasoned DevOps Engineer with a rich background that spans multiple industries and technologies. With foundational training as a Nuclear Engineer in the US Navy, Drew brings a meticulous approach to operational efficiency and reliability. His expertise lies in cloud migration strategies, CI/CD automation, and Kubernetes orchestration. Known for a keen focus on facts and correctness, Drew is proficient in a range of programming languages including Bash and JavaScript. His diverse experiences, from serving in the military to working in the corporate world, have equipped him with a comprehensive worldview and a knack for creative problem-solving. Drew advocates for streamlined, fact-based approaches in both code and business, making him a reliable authority in the tech industry.