Topic 6. DOM Manipulation Using createElement, appendChild, insertBefore, removeChild, etc.

Topic 7. Manipulating CSS Class Properties Using JavaScript

DOM Manipulation

What is the DOM

The DOM or Document Object Model is a model of the webpage that is loaded into the browser. Each of the elements on the page is an object in the DOM. The top level element of the dom is the document or the html element. Everything inside the html tags is a part of the document. The head and body are also objects and are children of the html. This pattern continues down through the rest of the document.

Manipulating HTML Elements

As objects, each element in the DOM has properties and methods. Using a scripting language such as JavaScript, the these elements can be manipulated. Elements can be added or removed, and their contents and attributes can be added and changed.

One of the most common ways of manipulating HTML elements is to change the text inside an element. This is done with .innerHTML and the assignment operator. Throughout the next section there are examples using .innerHTML.

Here is the syntax for .innerHTML

element.innerHTML = "New content";

Manipulating CSS Class Properties

In addition to being able to manipulate the HTML of a page, it is also possible to manipulate the CSS of the page. Style properties can be changed and added. Throughout the next section there are examples of adding and changing CSS attributes.

The syntax for for changing a CSS style is shown below. Notice that the style property is written in camelCase rather than hyphenated.

element.style.styleProperty = "value";

This works, but it is not the best solution. It adds an inline CSS style to the page instead of keeping the CSS separate from the HTML. A better approach is to add a class name to the element that refers to a styling rule in the CSS document for the page.

element.classList.add('className');

Selecting Elements

To change an element in the DOM, first it needs to be selected. There are several ways to select elements including getElementById(), getElementsByTagName(), getElementsByClassName(), querySelectorAll(), and .collection.

.getElementsById()

.getElementById() is the simplest way to select an element. To use this method, the element to be selected needs to have an id. Then that id can be inserted between the parenthesis to return that item. The example below will select the div with an id="output" and save it in the variable select. Then content is added with .innerHTML.

<div id="select"></div>

// in script tags
let select = document.getElementById('select');
select.innerHTML = "Inserted text goes here;

.getElementsByTagName()

.getElementsByTagName() will return an HTMLCollection of all the tags of that type. An HTMLCollection is similar to an array, in that you select an element with an index number, use a for loop, and use the length property to find out how many elements it has. However you can't use methods like pop(), push(), or join() on it. To use getElementsByTagName(), add a tag in the parenthesis. Then select the element from the HTMLCollection. The example below underlines the third h3 on the page.

var headings = document.getElementsByTagName('h3');
//select the third h3 on the page.
headings[2].style.textDecoration = "underline";

.getElementsByClassName()

.getElementsByClassName() will select all elements that have the specified class name and return an HTMLCollection. To use this method, the element you want to select needs to have that class name. The example below will bold this paragraph, and add content to the paragraph below.

Paragraph 2:

let added = document.getElementsByClassName('added');
// will add content to first element and bold the second.
added[1].innerHTML += "Content added here.";
added[0].classList.add('bolder');

.querySelectorAll()

.querySelectorAll() will select all of the elements with the specified id, class, type, attribute, attribute value, etc, and return the results in a NodeList. A node list is similar to an HTMLCollection, except it is a list of nodes instead of a list of elements. The desired element can then be selected with an index number. This is the most versitile option for selecting elements from the DOM. Here are some examples.

// select all p elements where the parent is a div.
let w = document.querySelectorAll("div > p");


// select multiple types of elements, (all headings)
let x = document.querySelectorAll('h1, h2, h3, h4, h5, h6');

// change all headings blue using a for loop.
for (let i = 0; i < x.length; i++) {
x[i].classList.add('colorBlue');


// select by class name
let y = document.querySelectorAll('.yellow');

// change the second element with class name of yellow to yellow.
y[1].classList.add("colorYellow");


// select type of element, (title of document)
let z = document.querySelectorAll('title');

// Add document title to div w selected above.
w[1].innerHTML = "Document title: " + z[0]innerHTML;

HTML Object Collection

This method directly selects the type of element that is stated and returns them to in an HTMLCollection. Or if there is only one, such as the head, body, title, etc, you can directly manipulate it.

// select the body
document.body.classList.add("colorChange");

You can refresh the page to reset original CSS properties.

Using Selection to make changes to the DOM

I have demonstrated several ways of manipulating the DOM already, by changing the contents of the innerHTML and changing CSS style properties. Here are some other changes that can be made to the DOM.

Add New Element to Dom

Adding a new element to the DOM takes place in several steps. First create a new element, then create a text node. Append the text node to the element, then append the element to a parent element in the DOM.

createElement()

Use createElement to create a new element and add content to it.

let newPar = createElement('p');
newPar.innerHTML = "2. This paragraph is appended to the end of parentDiv.";

appendChild()

Now use appendChild to add the new element to a parent element in the DOM. See the results below the insertBefore() section.

document.getElementById('parentDiv').appendChild('newPar');

insertBefore()

As an alternate to using appendChild, insertBefore can be used to insert a new element before an existing element. In order to do this, you need to know identify the parent div, and then insert it before a child of the div.

insertBefore() takes 2 paramenters, the new element to be inserted, and the child element that it will be inserted before. The syntax is parentElement.insertBefore(newElement, childElement);

// create and fill new p
let secondP = document.createElement('p');
secondP.innerHTML = "3. This paragraph is inserted before the first child of parentDiv.";

// identify the parent div.
let parentDiv = document.getElementById('parentDiv');

// insert new p before first child of parent div
parentDiv.insertBefore('secondP', parentDiv.childNodes[0]);

1. This is the original paragraph of parentDiv.

Notice that appendNode() inserted the paragraph as the last element of the div, and insertBefore() added the paragraph before the specified element in the div.

Remove Element From Dom

To remove an element from the DOM, you need to be able to identify the element to be removed as well as its parent element.

removeChild()

Remove child can be used to remove an element from the DOM. In order to remove an element, first identify the parent element of the element to be removed. Then identify the child element to be removed.

Then use the syntax parentElement.removeChild(childElement);

The example removes the 3rd child of the div below.

// identify parent
let parent = document.getElementById('parent');
// identify child
let child = parent.querySelectorAll('p');
// remove child
parent.removeChild(child[2]);

.parentNode

If you don't know the parent node, you can use parentNode in place of finding the parent node.

The syntax is childElement.parentNode.removeChild(childElement);

The examples removes the element with an id of p2. Notice that the order in which you click the buttons, will determine which element the "Remove third p" removes. However the remove p2 button always removes the paragraph with the id of p2. Selecting an element using getElementById is more precise and predictable than using querySelectAll()[index].

// identify child
let p2 = document.getElementById('p2');
// remove child
p2.parentNode.removeChild(p2);

paragraph 1

paragraph 2

paragraph 3

paragraph 4

Replace Existing Element

You can replace an existing element with a new element using replaceChild.

replaceChild

Using replaceChild, an existing element can be replaced with a new one. To use replaceChild, you need to identify the parent element, the child element to be replaced, and you need to create a new element

let p1 = document.getElementById('p1');
let p5 = document.createElement('p');
p5.innerHtml = "PARAGRAPH 5";
p1.parentNode.replaceChild(p1, p5);

Look at the 4 paragraphs in the previous section to see that p5 replaces p1 when button is clicked.