DEV Community

Cover image for Using Javascript to manipulate HTML elements via the DOM
Kabir Nazir
Kabir Nazir

Posted on

Using Javascript to manipulate HTML elements via the DOM

As you might be familiar, HTML and CSS are not ‘programming’ languages in the true sense. HTML is a ‘markup’ language that is used to create and display the elements of a webpage. CSS is a ‘stylesheet’ language that is used to write rules that will dictate the style and appearance of said elements. Although CSS does allow for some pseudo-programming with the help of pseudo-classes, it still isn’t considered as a programming language. Moreover, the functionality of CSS to manipulate elements during runtime is limited.

This is where Javascript comes in. It was initially created to be a programming language for the web browser, allowing us to be able to observe and manipulate the HTML and CSS code at run-time. The web browser interacts with Javascript by providing it a ‘host environment’ to run its commands on. This host environment provides certain objects and additional functions, which allow us to access additional features of the browser and elements of the HTML page at run-time.

The ‘window’ object

At the root of the browser, we have the window object. The window object is a global object in Javascript and provides methods to control the browser window through it. Here are some examples to make you understand better

    console.log(window.innerHeight); // This returns the height of the 
    // content area of the browser window

    function doSomething() {
        // some action
    }

    window.doSomething(); // Since window is a global object, we can use 
    // it to call functions with global scope too
Enter fullscreen mode Exit fullscreen mode

The window object is further divided into three components, namely the DOM, the BOM, and Javascript objects. We shall be further looking at how DOM works in this article.

DOM (Document Object Model)

The DOM is basically the container for all the objects that can be accessed and manipulated in a web page. Think of all the HTML elements in a web page as a collection of nested objects, for whom the root object is the DOM. The DOM is accessed in code by using the document keyword. So, we can access the <body> tag of the HTML page by calling document.body.

    document.body; // This is the object corresponding to the <body> tag
Enter fullscreen mode Exit fullscreen mode

Now say that you wish to access some other element of the page, like say a <p> element. Before we get to that, we need to first understand how elements in a web page are mapped to their corresponding objects in the DOM. Let’s take the example of a simple page

    <!DOCTYPE HTML>
    <html>
      <head>
        <title>This is the title</title>
      </head>
      <body>
        <p id="paragraph-1" class="class-1">This is a paragraph.</p>
        <ul>This is a list
          <li class="class-1">Item 1</li>
          <li>Item 2</li>
          <li class="class-1">Item 3</li>
        </ul>

      </body>
    </html>
Enter fullscreen mode Exit fullscreen mode

The DOM treats every HTML element in the above page as a node. There are 12 different types of nodes. However, we shall be looking only at 4 of them for now.

  1. document: The root node, present at the very top of the DOM.

  2. Element node: Nodes corresponding to the HMTL tags in the page.

  3. Text node: Nodes containing the inner text content of the tags.

  4. Comment: The comments that we include in between code. Although they are not visible on the page, they are still accessible by the DOM.

In the above code, the <html> tag is an element node. DOM follows a tree structure while organizing nodes. Hence, the <head> and <body> tags are element nodes that are considered as the child nodes of the <html> tag.

Selecting the nodes of these tags in Javascript is pretty simple as there as built-in functions for the same

    document.documentElement; // Points to the node of the <html> tag
    document.head; // Points to the node of the <head> tag
    document.body; // Points to the node of the <body> tag
Enter fullscreen mode Exit fullscreen mode

If we wished to select any other node, like say a <p> tag, DOM provides us with additional searching methods

document.getElementById

This method allows us to select an element in the web page that contains a particular id attribute.

    document.getElementById("paragraph-1"); // This points to the HTML 
    // element with id as paragraph-1
Enter fullscreen mode Exit fullscreen mode

document.querySelector

This method allows us to select the first element that matches the given CSS selector

    document.querySelector("li"); // This will return the node of the 
    // first <li> tag
Enter fullscreen mode Exit fullscreen mode

document.querySelectorAll

This method allows us to select all elements that match the given CSS selector

    document.querySelectorAll("li.class-1"); // This will return the     
    // collection of nodes of all <li> tags with the class class-1
Enter fullscreen mode Exit fullscreen mode

document.getElementsByTagName

This method allows us to select all elements of a particular tag

    document.getElementsByTagName("li"); // This will return the 
    // collection of nodes of all <li> tags
Enter fullscreen mode Exit fullscreen mode

document.getElementsByClassName

This method allows us to select all elements with the given class

    document.getElementsByClassName("class-1"); // This will return the 
    // collection of nodes of all elements with the class class-1
Enter fullscreen mode Exit fullscreen mode

Manipulating elements

Now that we have seen some basic methods to select elements in DOM, let us also see a few examples of how we can modify those elements too. Let us say we have a page like this

    <!DOCTYPE HTML>
    <html>
      <head>
        <title>This is the title</title>
      </head>
      <body>
        <p id="paragraph-1">This is a paragraph.</p>

    </body>
    </html>
Enter fullscreen mode Exit fullscreen mode

Change the content of an element

Let us say we wish to change the text of the first paragraph. We can do so by using the innerHTML property as follows

    document.getElementById("paragraph-1").innerHTML = "This is an edited 
    // paragraph."
Enter fullscreen mode Exit fullscreen mode

You can also add other tags within the value of innerHTML and the browser will render them as HTML text. For example, if you wished to change the text of the paragraph as well as make it bold, we can do something like this

    document.getElementById("paragraph-1").innerHTML = "<b>This is an 
    // edited paragraph.</b>"
Enter fullscreen mode Exit fullscreen mode

Change the style of an element

In order to change the style of an element, we use the style property. For example, in order to set a simple border to the paragraph, we write

    document.getElementById("paragraph-1").style.border = "1px solid red";
Enter fullscreen mode Exit fullscreen mode

In this post, we have attained a basic understanding of how DOM works and how it can be used to manipulate HTML elements. In the coming weeks, I shall be adding more posts into the deeper workings of Javascript. Till then, happy coding!

This post was originally published here on Medium.

Top comments (5)

Collapse
 
salmancreation profile image
Salman Ahmed

nice

Collapse
 
kabir4691 profile image
Kabir Nazir

Glad you liked it, Salman!

Collapse
 
mohsin708961 profile image
{{7*7}}

Awesome

Collapse
 
kabir4691 profile image
Kabir Nazir • Edited

Glad you liked it!

Collapse
 
kabir4691 profile image
Kabir Nazir

Oh. I haven't yet started React or Redux, so I don't know much about them. I'm spending a lot of time nowadays just to get my Javascript fundamentals right.