First steps into JavaScript – a practical guide 2

Modifying the DOM

by Iveta Karailievova Date: 26-10-2021 javascript DOM


In the previous aticle First steps into JavaScript – a practical guide we covered the basics of the DOM and its relation to us becoming JS literate. Now that we know how to access DOM elements, we can continue with learning how to change them.

But before we start, let's make sure we are familiar with a few facts:

When we talk about HTML elements in the DOM, we are actually talking about objects (that's their definition). Objects have properties (this means values, we can get or set) and methods (or actions, stuff we can do to/with the objects). The programming interface is the properties and methods of each object. Now that we cleared this up, we can start making modifications.

Changing content:

Many times, two simple properties will be all we need to use to do so. First of them is textContent. It uses straight text, does not parse HTML, and is therefor faster. Its output is text/plain.

On the other hand, we have innerHTML, which parses content as HTML, outputs text/html and thus takes longer.

Here is a simple example of how these two differ:

let myLink = document.getElementById('myLink');

 
myLink.textContent = '<a href="https://www.ma-no.org/">Ma-No Web</a>';

This will give us the following output: 

<a href="https://www.ma-no.org/">Ma-No Web</a>

But when we use:

myLink.innerHTML = '<a href="https://www.ma-no.org/">Ma-No Web</a>'; 

Our output will be:

Ma-No Web 

Changing CSS classes

This is easily done by using the classList property, and then the corresponding method (add, remove):

myElement.classList.add(className); 
myElement.classList.remove(className);

What would be the result of:

let h2 = document.getElementById('#heading2);
h2.classList.add('red','underlined');
h2.classList.remove('red'); 

Well, the selected element, in our case h2 would first receive two new CSS classes ("red" and "underlined") and then lose one class in the next step ("red);

As you can see, it's possible to add multiple comma-separated classes with the classList.add() method.

One important thing to notice here, which even though may seem obvious I think is good to remark: classList is a property, and can only be called on a single element, in our example we called it on a single h2 element, which we got accessed to by using the getElementById method. If we tried accessing a collection of elements, using getElementsByTagName for example, the classList property would not be available.

Changing styles

Sometimes we only need to make a quick change of the style of our element, and we can do this without having to create a CSS class simply by using the style property:

header.style.margin = '10px'; 

We just use an element's style property to directly modify its styles.

Working with attributes

It seems like a logical thing to want to be able to add or modify an element's attribute, and it is fairly easy to do so.We just need to make ourselves familiar with a few methods, with really self-explanatory names:

The setAttribute() method, where we pass two arguments - the name of the attribute we want to set and its value. The method then adds the specified attribute to an element, and gives it the specified value. In this way, we can change for example the element's ID, but also class, style, etc. Here's an example:

myElement.setAttribute("id","#01");

or
document.getElementById("myLink").setAttribute("href", "https://www.ma-no.org");

The removeAttribute() method removes the specified attribute from an element. Use the getAttribute() method to return the value of an attribute of an element. If the specified attribute already exists, only the value is set/changed.

Maybe are some of you wondering, if we can modify attributes with those methods, why not use them to also change the "style" attributes. Although it is possible, it is not recommended.

Instead we use properties of the Style object as we described earlier, because in this way we make sure that other CSS properties that may be specified in the style attribute will not be overwritten.

Adding new elements

We have to follow these steps to create and append new elements to our page:

  • first we create the element we need by calling the createElement DOM method, like this:
    let mySection = document.createElement('section');
    
    
  • now we have our new section created, but it is empty, we might want to append some elements to it. Those elements first need to be created too, so again, we use the createElement method and store these newly build elements in variables:
    let myArticle = document.createElement('article');
    
    
    let myParagraph = document.createElement('p');
    
    
  • Even though these variables are so far not visible to us, they hold references to DOM elements and because of this, we are able to use the methods we've mentioned before to add content:
    myParagraph.textContent = "whatever";
    
    
  • Nice! Now the elements exist somewhere out there, in the DOM. Let's put them together, using the appendChild method. First we append the paragraph to the article and the the article to the section:
    mySection.appendChild(myArticle);
    
    
  • Finally, we need to append our section to some element which already exists in the DOM, like for example 'main'. Remember, to access the 'main' element, we use for example the getElementByTagName method:
    document.getElementByTagName('main').appendChild('mySection);
    
    
  • And what if we need to replace or remove an element?

    We use either the replaceChild() or the removeChild() method, according to our needs. Notice that both methods call on the parent of the element you wish to remove. So to remove an element when we do not have direct access to the parent element can be done with this little trick:

    myElement.parentElement.removeChild(myElement);
    
    

A short recap:

After gaining access to our DOM elements, we want to modify them. This is done by either using their properties or methods. We can create and add new elements to the DOM, modify the elements' classes and style and modify their attributes.

And that's it! These are the basics you need to know so that we can move up a level and learn how to make more magical things happen, like reacting to events (such as mouse clicks or form inputs).

 
by Iveta Karailievova Date: 26-10-2021 javascript DOM hits : 2454  
 
Iveta Karailievova

Iveta Karailievova

Originally coming from a marketing background, decided to turn her life around and immerse herself into the wonderful exciting and most importantly – never boring world of technology and web development. Proud employee at MA-NO . Easily loses track of time when enjoying working on code. Big fan of Placebo, cats and pizza.

 
 
 

Related Posts

Node.js and npm: introductory tutorial

In this tutorial we will see how to install and use both Node.js and the npm package manager. In addition, we will also create a small sample application. If you…

How to connect to MySQL with Node.js

Let's see how you can connect to a MySQL database using Node.js, the popular JavaScript runtime environment. Before we start, it is important to note that you must have Node.js installed…

JavaScript Programming Styles: Best Practices

When programming with JavaScript there are certain conventions that you should apply, especially when working in a team environment. In fact, it is common to have meetings to discuss standards…

Difference between arrow and normal functions in JavaScript

In this tutorial we are going to see how arrow functions differ from normal JavaScript functions. We will also see when you should use one and when you should use…

JavaScript Arrow functions: What they are and how to use them

In this article we are going to see what they are and how to use JavaScript Arrow Functions, a new feature introduced with the ES6 standard (ECMAScript 6). What are Arrow…

How to insert an element into an array with JavaScript

In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript. For this we will use the splice function. The splice function will not…

What is the difference between primitives types and objects in JavaScript?

In this short tutorial we are going to look at the differences between primitive types and objects in JavaScript. To start with, we're going to look at what primitive types…

How to get DOM elements with JavaScript

When you access any element of the DOM, it is usual to save it in a variable. This is something that at first might seem very simple, but if you…

How to reverse an array in JavaScript

In this tutorial we are going to see how you can change the order of the elements of an array so that they are inverted. You could use a loop…

How synchronize the scroll of two divs with JavaScript

In case you have two divs of different sizes you may sometimes want to scroll both at the same time but at different speeds depending on their size. For example,…

How to use the codePointAt method in JavaScript

The JavaScript codePointAt method has more or less the same function as the charCodeAt method, used to get the 16-bit Unicode representation of the character at a certain position in…

How to check if a value is a number in JavaScript

In this short tutorial we are going to look at the various methods that exist to find out if a value is a number in JavaScript.   1. Using the isNaN() function   One…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration