First Steps Into Javascript – a Practical Guide

Part one: Introducing the DOM - what is it and why should I get to know it?

by Iveta Karailievova Date: 05-05-2020 javascript coding dom


For those who are new to web development, surely the amount of new terminology can sometimes be discouraging. But when it comes to learning JS, some of the first new concepts you definitively should wrap your head around is the Document Object Model and what it implies.

To keep it simple and not to resort to citing formal definitions, the DOM represents the website and its elements as a logical structure, resembling a tree with its branches. Each branch is a node, and each node contains objects.

DOM-model

When we have access to a certain node in the DOM, there are ways to gain access to other nodes in the DOM using its related nodes. We can move up or down the DOM tree, or we can move sideways staying at the same DOM level. This is also called traversing the DOM (which sounds super cool if you ask me).

But how can we make use of all this and how is it related to programming in JS?

Since the DOM allows us to access to all the elements of a web page, by using scripting languages, like for example JS, we can make modifications to them. In this way, we are able to change the document's structure, style, or content.

Moreover, the nodes from our imaginary tree allow to attach event handlers to them. Once an event is triggered, the event handlers get executed. This opens up a whole new world of possibilities to control the web page behavior to us. The most obvious ways we can make use of this are:

  • Reacting to user input – change the page’s content based on the data entered by the user, and even send those data to another server.
  • Using data received from APIs and use them to update the page's contents.

As we already said, the DOM has a tree-like structure: starting with the root element, the

tag. From here, each child element branches out. Usually, the root element is a parent to two child elements:and. The html tag is then parent to any elements within it — paragraphs, articles, sections, buttons, forms,etc. Those child elements can then have children of their own: a form will have labels and inputs, an article can have a heading, text content, links, etc.

How to access the DOM elements in JS

There are various ways available for us, but let’s start with using the “document” object and its methods.

  • document.getElementsByTagName(); As the name suggest, we need to specify the tag name in order to use this method. So, for example if we want to select all paragraph elements, we would use document.getElementsByTagName(‘p’); Of course, it would be useful to save this reference in a variable, for example like this: var paragraphs = “document.getElementsByTagName(‘p’); It is important to know that the getElementsByTagName() method returns an object of type HTMLCollection, or in other words, a collection of all elements in the document with the specified tag name. The HTMLCollection object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0. This is similar to how we would acces an array. But beware! A HTML collection is NOT an array object, so we cannot use Array methods like push(), pop() or indexOf(). But, in order to access the first element in our collection, we use the following: var firstParagraph = paragraphs[0];

    We create a constant called firstParagraph and then we assign the first (because, as it always is the case with indexes, we start counting at 0) element of our “ paragraphs” HTML collection to it.

  • document.getElementById(); Very useful, but careful – as you can see if you observe its name, this method returns only ONE element, not a collection. This makes perfect sense, if you consider that a well structured and correctly designed web should only have one element per ID.
  • document.getElementsByClassName(); Selects all elements with matching class name, for example: var redBackground = document.getElementsByClassName(“bg_red”); this line of code enables us to reference all elements with class “bg_red” with the constant called redBackground;
  • document.querySelector(); This method returns the first element in the DOM that matches the given selector(s). The selectors used may be tag names, classes, id attributes, or a mixture of the three:
    • document.querySelector('article') — returns the first "article" element
    • document.querySelector('.text-center') — returns the first element with class “text-center”
    • document.querySelector('#main') — returns the element with id attribute “main”
    • document.queryselector('h2.text-center') — returns the first "h2"element with class “text-center”

There is one more method I would like to add to the list:

document.querySelectorAll();

It returns a Node List object, which is almost the same as the HTML collection object which we commented earlier. In fact, some older browsers return a Node List object instead of an HTML Collection for methods like getElementsByClassName().

This seems a bit confusing, so let’s see what similarities and differences there are between a node list object and a HTML collection object:

  • They both resemble an array-like list of objects but they are not arrays! you cannot use Array Methods, like valueOf(), push(), pop(), or join() on them.
  • Both have a length property, which gives us the number of items in the list.
  • Both use an index, (starting with 0) so that each of their items can be accessed or looped through similar to how we would be accessing elements in an array.

BUT:

  • HTML Collection items can be accessed by their name, id, or index number.
  • Node List items can only be accessed by their index number.
  • Only the Node List object can contain attribute nodes and text nodes (we haven’t covered these yet).

Lastly, there are DOM methods and properties which allow us to use the “family relationships” between the DOM elements to navigate and select them (this is the actual “traversing of the DOM”) . But why do we need to learn to traverse the DOM, if we know methods such as document.querySelector?

Because it’s always quicker and easier to move from an element to another, then doing a full search.

You can traverse in three directions:

  1. Downwards: element.children — returns a HTML Collection containing all child elements of element
  2. Sideways element.nextElementSibling + element.previousElementSibling — these allow us to iterate through elements on the same relationship level, like between list items
  3. Upwards element.parentElement — element's parent element (any given element can only have up to one parent)

To summarize – the DOM allows JavaScript to access and manipulate the page content. In order to access the elements, we need to make ourselves acquainted with using the corresponding object methods, like document.getElementById(), document.getElementsByClassName(), getElementsByTagName() and document.querySelector().

 
by Iveta Karailievova Date: 05-05-2020 javascript coding dom hits : 1821  
 
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

Validating HTML forms using BULMA and vanilla JavaScript

Today we are going to write about contact forms and how to validate them using JavaScript. The contact form seems to be one of the top features of every basic home…

A FULFILLED PROMISE - Using the FETCH API to make AJAX calls

In this article we talked about what AJAX calls are and how to use them in a traditional way, by using the XMLHttpRequest (XHR) object. In short, thanks to AJAX…

How to use Parallax.js effect on your website

Today, we're going to write about the parallax effect, similar to parallax scrolling, and how to implement it to improve your landing page. In webdev, they say mobile first -…

How to make the website's dark mode persistent with Local Storage, CSS and JS

Recently we wrote about how to do a switchable alternative color mode or theme, a very useful and popular feature to websites. Today’s article is going to be about how…

A Java approach: While loop

Hello everyone and welcome back! After having made a short, but full-bodied, introduction about cycles, today we are finally going to see the first implementations that use what we have called…

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

A Java approach: The Cycles - Introduction

Hello everyone and welcome back! Until now, we have been talking about variables and selection structures, going to consider some of the fundamental aspects of these two concepts. Theoretically, to…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

Javascript: what are callbacks and how to use them.

Today we are going to learn about a concept that is widely used in javascript and that is used quite a lot by today's frameworks, libraries, especially NodeJS. This is…

A Java approach: variables - use case

Hello all friends and welcome back! After the introduction made on the variables, we try to analyse some critical issues that may arise in quite common situations. Let's start by analysing…

HTTP Cookies: how they work and how to use them

Today we are going to write about the way to store data in a browser, why websites use cookies and how they work in detail. Continue reading to find out how…

The package managers npm and yarn: main differences

Npm and yarn are package managers that help to manage a project’s dependencies. A dependency is, as it sounds, something that a project depends on, a piece of code that…

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