Copyright

Using JavaScript to Work With the Document Object Model: Use & Examples

Instructor: Alexis Kypridemos

Alexis is a technical writer for an IT company and has worked in publishing as a writer, editor and web designer. He has a BA in Communication.

In this lesson, we'll explain how to use JavaScript and the Document Object Model, DOM, to add child HTML elements to parent nodes in the browser view of a document, as well as how to dynamically add CSS properties to elements.

Manipulating the DOM with JavaScript

The DOM, Document Object Model, and how it can be manipulated using JavaScript was explained in another lesson, available here:https://study.com/academy/lesson/modifying-elements-attributes-classes-styles-in-the-dom.html.

In this lesson, we'll expand a little bit in our explanation of the various ways JavaScript can exploit the DOM. For instance, in the introductory chapter on JavaScript manipulation of the DOM, we discussed how to make changes to an element's class, its attributes, and even its style properties. We'll provide some additional information on manipulating styles later in this lesson, but for now, let's have a look at how we can use the DOM to modify the HTML elements themselves.

Adding Children to Parent Nodes

One example of modifying the actual HTML elements, which you'll remember are called nodes in DOM terminology, is to use JavaScript to create additional elements inside them. From previous chapters, you'll know that when one HTML element includes another, like a <div> that includes a <p>, this relationship is referred to as "parent-child" in DOM terms. The <div> would be the parent in this case.

So let's see an example of adding children elements to parent nodes. To make things interesting, we'll have a look at an HTML document that includes a <div> that has an ID, and a second <div> that has a class, but no ID. This way we'll get a chance to use a couple of different JavaScript methods to identify nodes.

Here's our code:

<!DOCTYPE html>
<html>
<body>
<div id = "main">
<p>This is the div's first paragraph, but we'll use JavaScript to add a second one.</p>
</div>
<div class = "body">
<p>This paragraph has a class of "body", but no ID.</p>
</div>
<script>
var newParagraph = document.createElement("p");
var text = document.createTextNode("We used JavaScript to add this paragraph.");
newParagraph.appendChild(text);
var newerParagraph = newParagraph.cloneNode(true);
var main = document.getElementById("main");
var bodyDiv = document.getElementsByClassName("body");
main.appendChild(newParagraph);
bodyDiv[0].appendChild(newerParagraph);
</script>
</body>
</html>

OK, so let's explain what we did above. In the HTML <body>, we have two <div> tags, each including a paragraph.

In the JavaScript code, we start off by defining the new variable called newParagraph. The key here is using the document.createElement("p") method. As you see, this method takes the argument "p", which indicates the type of HTML element we want to create.

Similarly, we create the variable text and add some text to it using the document.createTextNode() method.

So far, this new paragraph and text are not connected in any way, so we have to specify that we want the text placed inside the paragraph with the newParagraph.appendChild(text); line. The appendChild() method makes the text a child of the parent paragraph node. We'll use the same approach again in this script.

The next command is interesting: var newerParagraph = newParagraph.cloneNode(true);. We first create a new variable with the inspired name of newerParagraph and then use the cloneNode() method to create a copy of the previously-created new paragraph, so that we now have two of them at our disposal. We have to do this because we can append each new child element only once in an HTML document.

Next, we identify the <div> that has an ID of "main" using the document.getElementById() method. For the <div> that only has a class, we identify it by using the getElementsByClassName() method instead.

We store the results in separate variables, main and bodyDiv respectively.

In the last two lines of the script, we add our new paragraphs to the div's again using the appendChild() method.

Note that for the div we identified by class, we have to specify which one we're talking about, by stating its index, [0]. Remember, JavaScript begins counting at 0, not 1, so 0 indicates the first element with this class in the document.

Adding CSS Dynamically

As mentioned above, another use of the DOM is to dynamically add style properties (CSS) to elements, without having to worry about affecting the style rules written in any .css stylesheet files linked to the document.

Remember, any changes made using JavaScript and the DOM only affect the way the document appears in the browser; the document's original code remains unchanged.

To unlock this lesson you must be a Study.com Member.
Create your account

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back
What teachers are saying about Study.com
Try it risk-free for 30 days

Earning College Credit

Did you know… We have over 200 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Transferring credit to the school of your choice

Not sure what college you want to attend yet? Study.com has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

Create an account to start this course today
Try it risk-free for 30 days!
Create an account
Support