...

/

DOM Manipulation with JavaScript

DOM Manipulation with JavaScript

Introduction to DOM manipulation using JavaScript

We'll cover the following...

Introduction

To achieve interactivity, JavaScript must manipulate the DOM. Because the DOM is tree-like nature, we will cover each of the following steps.

  • Querying and selecting a certain element in the DOM

  • Traversing elements in the DOM

  • Creating an element in the DOM

  • Updating an element in the DOM

  • Removing an element in the DOM

Let’s go over each of these to become more comfortable creating dynamic web pages.

Query element

A vital part of DOM manipulation is finding the right element. To do that, query over the document object and use methods find the right elements. Some methods are as follows.

  • getElementsByTagName(x): Method for getting an object (NodeList) with all elements with the tag name same as string x

  • getElementsByClassName(x): Method for getting an object (NodeList) with all elements with the class attribute same as string x.

  • getElementById(x): Method for getting an object (Element) with the id attribute same as string x.

Using these methods, we can access certain elements without traversing the tree-like structure of the DOM.

NOTE: The NodeList class of objects is a list of document nodes which can be traversed and indexed, similar to that of arrays in JavaScript.

Take a look at the following example. ...