DOM Manipulation For Newbies

DOM Manipulation For Newbies

Introduction

So whenever we open a website there’s usually buttons that link to other pages of the webpage or a sign up button to create a profile on the site. The DOM is what makes these actions possible,now,before we get into the DOM, we need to understand that JavaScript doesn’t understand HTML elements as tags.

DOM Tree

But JavaScript can only understand HTML elements as a tree like structure called DOM, so HTML elements have to be interpreted into these tree like structures because that’s the only way Javascript will understand it.

WHAT IS THE DOM?

DOM is a language interface that allows script(code) to access and change the content, structure and style of a document. The DOM helps JavaScript get access to the HTML and also the CSS of the webpage. It also helps Javascript add behavior to the website.

The main things we need to know for DOM Manipulation are:

  • Selecting Elements in the DOM

  • Changing Styling in the DOM

  • Manipulating the Elements

  • Event Handling in the DOM

The first step in manipulating elements with the DOM involves selecting the elements in the DOM

SELECTING ELEMENTS IN THE DOM

The methods below help JavaScript find and select elements in the DOM

  • document.getElementById()

  • document.getElementByClassName()

  • document.getElementByTagName()

  • document.querySelector()

  • document.querySelectorAll()

i)document.getElementById()

This is a common method used to select elements, this method gets an element based on the id of the element

 <body>
    <div class="paragraphs">
        <p id="par1">this is a sentence</p>
        <p id="par2">this is a sentence</p>
        <p id="par3">this is a sentence</p>
        <p id="par4">this is a sentence</p>
    </div>
    <script>
        let headless = document.getElementById("par2");

        function headies(){
            console.log(headless);
        };
        headies();
    </script>
</body>

ii)document.getElementByClassName()

This method is used to get all the elements under the class specified regardless of the type of tag. This usually results to an array of elements

<body>
    <div class="content">
        <p>this is a sentence</p>
        <p>this is a sentence</p>
    </div>
    <div class="content">
        <h1>this is heading 1</h1>
        <h2>this is heading 2</h2>
    </div>
    <script>
        function headies(){
            let rusty = document.getElementsByClassName('.content');
            console.log(rusty);
        };
        headies();
    </script>
</body>

iii)document.getElementByTagName() This method is used to get all the elements under a HTML tag name. This also leads to an array of elements.

         <body>
    <div class="paragraphs">
        <p id="par1">this is a sentence</p>
        <p id="par2">this is a sentence</p>
        <p id="par3">this is a sentence</p>
        <p id="par4">this is a sentence</p>
    </div>
    <script>
        function headies(){
            let parg = document.getElementsByTagName('p');
            console.log(parg);
        };
        headies();
    </script>
</body>

iv)document.querySelector() This gets any element based on class, id or tag name. But it can get any element, which is usually the first element of a class or tag name.

       <body>
    <div class="content">
        <p id="par1">this is a sentence</p>
        <p id="par2">this is a sentence</p>
        <p id="par3">this is a sentence</p>
    </div>

    <script>
        let data = document.querySelector('.content');
        console.log(data);
    </script>
</body>

v)document.querySelectorAll() This method gets all the elements of a class or tag name and it also gives us an array of elements

 <body>
    <div class="content">
        <h1>this is heading 1</h1>
        <h2>this is heading 2</h2>
        <h3>this is heading 3</h3>
    </div>


    <script>
        let anew = document.querySelectorAll('.content');
        console.log(anew);
    </script>
</body>

MANIPULATING ELEMENTS IN THE DOM

In order to learn how to change elements in the DOM, we need to learn how to;

  • Use innerHTML

  • How to add or create elements

  • How to replace an element

  • How to remove an element

I) innerHTML

This is used to change the content of the element, especially the text content. But this method is prone to errors.

<body>
    <div class="box">
        <h1>this is heading 1</h1>
        <h2>this is heading 2</h2>
    </div>


    <script>
        let anew = document.querySelector('h2').innerHTML='Hi I`m Daniel';
        console.log(anew);
    </script>
</body>

II)Creating or Adding new Element:

This is another way to change the content of elements in HTML. There are two ways this can be done:

a) New Element + New Content

This is the long method, in this method. We will first create a new element, then we will create a new text content. The text content will then be added to the new element.

Step1: Create new Element

     <body>
    <div class="box">
        <h1>this is heading 1</h1>
    </div>

    <script>
        let boxx = document.querySelector('.box');
        let newElement = document.createElement('a');
    </script>
</body>

Step2: Create new Text Content:

<body>
    <div class="box">
        <h1>this is heading 1</h1>
    </div>

    <script>
        let boxx = document.querySelector('.box');
        let newCont = document.createTextNode('This is a link');
    </script>
</body>

Step3: Add new Content to new Element:

<body>
    <div class="box">
        <h1>this is heading 1</h1>
    </div>

    <script>
        let boxx= document.querySelector('.box');
        let newElement = document.createElement('a');
        let newCont = document.createTextNode('This is a link');

        newElement.appendChild(newCont);
        boxx.appendChild(newElement);

    </script>
</body>

b) New Element + (“Content”):

This method doesn’t need a new text content created, the content can be directly added to the new element.

<body>
    <div class="box">
        <h1>this is heading 1</h1>
    </div>

    <script>
        let boxx = document.querySelector('.box');
        let neew = document.createElement('p');
    </script>
</body>

Step 2: Add content:

<body>
    <div class="box">
        <h1>this is heading 1</h1>
    </div>

    <script>
        let boxx = document.querySelector('.box');
        let neew = document.createElement('p');

        neew.appendChild('I don`t know');
        boxx.appendChild(neew);
    </script>
</body>

III) Removing an Element

This method allows Javascript to remove an element from a webpage.

<body>
    <div class="box">
        <h1>this is heading 1</h1>
    </div>

    <script>
               let boxx= document.querySelector('.box');
        let newElement = document.createElement('a');
        let newCont = document.createTextNode('This is a link');

        newElement.appendChild(newCont);
        boxx.appendChild(newElement);

        boxx.removeChild(newElement);
    </script>

IV) Replacing an Element This method allows Javascript to replace an old element with a new element

<body>
    <div class="box">
        <h1>this is heading 1</h1>
    </div>

    <script>
        let boxx= document.querySelector('.box');
        let newElement = document.createElement('a');
        let newCont = document.createTextNode('This is a link');

        newElement.appendChild(newCont);
        boxx.appendChild(newElement);

        boxx.replaceChild(p,newElement);
    </script>
</body>

CHANGE STYLING IN THE DOM

The method we will be focusing on only allows Javascript to change style that exists inside an element tag, it cannot change a style that exists as a separate file, such as a stylesheet.

Methods to Change Styling with Javascript

a) Style.property:

This method can only change one CSS style property of an element.

<body>
    <div class="box">
        <h1 style="color:red;">this is heading 1</h1>
    </div>

    <script>
       document.querySelector('h1').style.color = 'green';
    </script>
</body>

b) Style.cssText:

This method allows Javascript to change multiple CSS styles of an element.

<body>
    <div class="box">
        <h1 style="color:red;">this is heading 1</h1>
    </div>

    <script>
       document.querySelector('h1').style.cssText = "color:red; font-size:18px;";
    </script>
</body>

c) setAttribute():

This method also allows Javascript to change multiple CSS styles of an element.

<body>
    <div class="box">
        <h1 style="color:red;">this is heading 1</h1>
    </div>

    <script>
       document.querySelector('h1').setAttribute('style', "color:yellow; font-size:30px;");
    </script>
</body>

EVENTS IN THE DOM

An event is an action that occurs when a user is trying to interact with the webpage either by clicking a button, submitting a form etc.

There are two types of events:

  • Event handlers

  • Event Listeners

EVENT HANDLERS

This involves the use of event handler properties of an element, they usually have names that begin with ‘on’ e.g click event is onclick while mouseover event is onmouseover.

<body>
    <div class="box">
        <h1 style="color:red;">this is heading 1</h1>
        <button class="btn">About</button>
    </div>

    <script>
       const button = document.querySelector('.btn');
       button.onclick = function btn_i(){
        alert('Go away');
       }
       btn_i();
    </script>
</body>

Event Listners

This method adds an event to the element or uses event listeners to add events to the element. Events can be added or removed from the element with this method.

addEventListener()

i) .addEventListener() This function adds an event to the to the element, there are 3 parameters passed on event listeners; the event, the function, and useCapture.

<body>
    <div class="box">
        <h1 style="color:red;">this is heading 1</h1>
        <button class="btn">About</button>
    </div>

    <script>
       const button = document.querySelector('.btn');
       button.addEventListener("click",function btn_i(event){
        alert("How you doing?");
       })

    </script>
</body>

The event : This is the string that specifies the event that is being carried out.

The function: This is the function that works when the event is performed.

useCapture: is a Boolean value that specifies, whether to use event bubbling or not. This is not a compulsory value of event listeners. Event listeners allow multiple events or functions to be added to a single event handler.

ii) .removeEventListener() This function removes any event listeners previously attached to an element, it uses the same three parameters that were used for addEventListeners().

<body>
    <div class="box">
        <h1 style="color:red;">this is heading 1</h1>
        <button class="btn">About</button>
    </div>

    <script>
       const button = document.querySelector('.btn');
       button.removeEventListener("click",function btn_i(event){
        alert("How you doing?");
       })

    </script>
</body>