Looking to create a button to change a web page’s background color, build a form that will allow users to add a comment directly to your page, or remove content when a user clicks an “X” button? You’ll need to know how to manipulate the Document Object Model, or DOM, to do all of these things.
The DOM is the structure a web browser generates from an HTML file. The browser reads the HTML file and generates a version of the elements that is formatted for your JavaScript code to communicate with. We need this “translated” version of the HTML so that we can use JavaScript to talk to the elements on the page. If JavaScript could not talk to the DOM, we wouldn’t be able to use JavaScript to change the appearance of the page.
You can picture the DOM as a kind of hanging mobile sculpture, where each node of the mobile is a different HTML element. You could also imagine it as a family tree, where the “root” is the parent of all the other elements in the tree. That means that the largest containing element, <html>, contains all the other elements in the tree. Here’s an example:
Here’s what the above HTML looks like as a DOM tree:
We frequently use family terminology in referencing parts of the DOM. In the above example, the <html> tag is the parent of the <head> and the <body> and the ancestor of all of the other elements. The <li> elements are the children of the <ul> element. Similarly, the <li>s are sibling elements.
The HTML file itself provides a good way to visualize the Document Object Model, because it’s the file that helps the browser create it. When you indent each subsequent “layer” of HTML, you give yourself a good visual of the nesting of the DOM. Remember, the DOM is created by the browser when it reads your HTML. Your HTML document is the template which creates the DOM.
When building a website, you might want to build functionality for the DOM to change in response to a user action. Every web framework?— from Angular, to?React, to?jQuery?— provides some way to adjust the DOM. The best ways to first encounter DOM manipulation are to use plain JavaScript or, even better, use jQuery.
In each, you must first tell the JavaScript how to find the element on the page (we call this selecting the element) and then manipulate it.
How No-Frills JavaScript Interacts With the DOM
In JavaScript, there are separate methods for selecting elements by element type, class, and id. Below are the plain JavaScript methods for selecting elements.
Once you’ve selected the element, you can use a number of methods to change or add to it. For example, if you’d like to add some content to the page, you can append HTML using the .appendChild(element) method, like this:
You can append a new child HTML element to any part of your page by first selecting the element you want to be a new parent:
If you want to append an HTML element with content inside it, you’ll create a text node using the .createTextNode() function like this:
You can see that something as simple as adding a div with some text is already getting quite complex. This is where jQuery comes in to simplify our DOM manipulation.
Simplifying DOM Manipulation With jQuery
jQuery?is a?JavaScript?library that provides tools to make life simpler for web developers. Behind the scenes, the jQuery source code is written in JavaScript. That means that anything we do in jQuery could be accomplished in JavaScript with more code. jQuery is designed to simplify DOM manipulation, and its syntax is easier to grasp. It uses?CSS-style selectors to pick DOM elements (elements from the HTML). That is, you can select an element by using its tag, class, or id. For example:
$(‘span’) will select all of the span elements,
$(‘.container’) will select all of the elements with a class of container, and
$(‘#hero-image’) will select the element with the id of “hero-image”.
Because CSS selectors can get complex, you can select very specific elements on your page.
Once you have selected a DOM element, you can change it at will using a large array of jQuery manipulation methods.
Here is an example of using jQuery to manipulate some HTML.
The HTML:
DOM’s JavaScript component:
The above code will change all of the paragraph elements on the page to have a value of “Boo!”. Go to a webpage with jQuery loaded on it, like css-tricks.com, open the console with `command` + `option` + `j`, and paste that code into the prompt. When you execute that code, you’ll notice all of the paragraphs will have changed to say “Boo!”
As you’re working with jQuery to manipulate DOM elements, you are almost always either getting or setting a value. If you want to find out the current value of some attribute, you are getting. If you want to change the value, you should be setting. This is the pattern:
- Getting a value: $(“CSS Selector”).someJqueryMethodName()
- Settings a value: $(“CSS Selector”).someJqueryMethodName(valueToSet)
Notice that getting a value doesn’t require an argument to the jQuery method, but setting a value does.
Following that pattern, we could get the value of the text of an element on the page:
- Get the text of the readme (it lives inside of an article tag): $(‘p’).text()
- Set the text of the readme to: “Boo!”: $(‘p’).text(“Boo!”)
Some jQuery methods require an argument in either case. For example, the .css() jQuery method works as follows:
- Get the background color: $(‘p’).css(“background-color”)
- Set the background color to blue: $(‘p’).css(“background-color”, “orange”)
Some of the most common jQuery DOM manipulations are:
You can use these manipulation methods, along with event listeners, to change your page in response to user actions.
- Append HTML content as a child of the current selected element: $(‘.selected-element’).append(htmlContent)
- Add/remove a new class to/from the selected element: $(‘.selected-element’).addClass(className) / .removeClass(className)
- Replace all of the current HTML content within the selected element with the inputted htmlContent: $(‘.selected-element’).html(htmlContent)
- Replace the current text content of the selected element with new text: $(‘.selected-element’).text(newTextString)
- Change the value within an input element: $(‘.selected-input-element’).val(newValue)
- Remove the selected element from the page: $(‘.selected-element’).remove()
You can use these manipulation methods, along with event listeners, to change your page in response to user actions.
DOM at 足球竞彩网 Assembly
In 足球竞彩网 Assembly’s full-time Web Development Immersive and part-time Front-End Web Development courses, students learn DOM by visiting jQuery-enabled websites like CSS-Tricks and using the console to alter the pages in front of them. Changing all of the titles to some goofy text gives students a sample of the power of this tool.
Students also dive into and read the jQuery documentation to find out about the most useful DOM manipulation methods. We make sure to emphasize .append, .addClass, .html, .text, and .val. Then, we introduce DOM events so that students’ sites can detect clicks, form submissions, scrolling, and keypresses. Much of the time, our response to these events is to manipulate the DOM accordingly. When a user presses a button, it can change the appearance of the web page. We do this by listening for the button press and then manipulating the DOM to impact the page.
Ask a Question About Our Coding Programs
Meet Our Expert
Cory Fauver is a Web Development Immersive instructor and former Front-End Web Development instructor at 足球竞彩网 Assembly’s San Francisco campus. He left his early career in math education to teach himself web development while building a company with two close college friends. While their product didn’t work out, they left that experience with skills that they’re all using today. Cory enjoys sharing the methods and resources he used to learn HTML, CSS, and JavaScript. When he’s not at a computer, he loves playing ultimate frisbee, backpacking, and being outdoors.
“Now is a great time to learn web development because there are so many quality resources available to find and use. Once you gain that skill, there’s an entire world of learning to do!”
Cory Fauver, Web Development Immersive Instructor, GA San Francisco