Blog

BASICS: A USER PERSPECTIVE ON JAVASCRIPT DOM

EBS Integrator
Feb 23, 2020,

JavaScript DOMWelcome to another instalment of our “Basics:” diary, in which we have been making steady progress to a better understanding of the Internet and its magic formulas. In our last article, we touched on the subject of presenting markup languages powering the user interfaces of today. So, before we say goodbye to our beloved “front-end” layer…. It’s paramount to crack the shell of interoperability within this level. Here we’ll talk JavaScript, CSS, and HTML – but not before diving into some history.

MARKUP LANGUAGES SHORT CONTINUATION

Let us recollect on what we can find in the front-end layer:

HTML– is our stack of gears. Every website on the internet is a structured file stored on a device. Always ready to be sent to anyone that requests it.  Whatever information is passed through the www, needs to be understood not only by users but computers as well. Therefore, we use markup to help our dear computer in differentiating . What’s for us to see and what’s for him to do.

CSS – is our oil. A car’s gears will grind and chip away if there is not enough oil pressure. Similarly, text by itself is tedious to look and navigate through. Meaningful placement, highlights and colour, images, and responsive design contribute to bringing our paragraphs to life. But there is so much you can do, with the above. Two gears turning and some engine oil to keep the scraping to a minimum isn’t going to cut it. We are in need of some interaction to happen.

JavaScript – is our heap of belts. Provides a medium for our primitive mono-system, to come out and play on the scene with other structures. Thus contributing to the rise of a multi-system environment (transmission belts, HVAC). Several customizable interactions are made available to the user, through the power of scripting.

JavaScript DOM

JS as OOP?

By definition, JavaScript is a fully-fledged object-oriented programming (OOP) language. In other words, while HTML and CSS are used to annotate a document. JavaScript employs several sets of instructions and variables to produce an output. Elaborating on the OOP side will take just as much as investigating the “in” and “outs” of a programming language. Therefore we will leave it for another time. The main takeaway needed to continue our research is that OOP adds classes and objects. Think of classes as templates and of objects as results generated by those templates.

For instance, a car service register keeps records of several manufacturers, models and detailed description on changing parts and general maintenance. While every car has its own proprietary systems design (Mercedes engine vs Toyota engine) they share the same template. Name, number, technicalities. A template entry for a specific car resembles an object attributed to a specific class. As ruled by “The Clean Code” classes receive their names by convenience. So…  We’ll call this one: “car maintenance register”. Now, whenever you need to access data for a particular auto vehicle, all you have to do is search through a specific number of objects within the “car maintenance register” class, and voilà: you can view & manipulate the object’s properties according to your needs.

JAVASCRIPT DOM – FROM STEAM TO COMBUSTION ENGINE

The internet has come a long way and its initial purpose has changed since the 90s. Starting from the first web browser, developed in 1990 by Tim Berners-Lee for the NeXT Computer, we have witnessed an indisputable growth.

What was once lines of text, came to be a fully customizable experience and is yet to achieve its final phase. Our story starts in September 1993, with the release of NCSA Mosaic. The first time a browser displayed images in line with the text. Prior browsers provided a non-seamless experience since they required the user to go through a few steps before viewing a multimedia piece.

Marc Andreessen, who was at the time the leader of Mosaic team, went to start up a company later known as Netscape Communications Corporation. While they did matter for the innovation of current competition, something was missing. There was a “gear” here, a “gear” there, but the “belt” to pull them together was missing. Addressing this demand, Netscape came up with JavaScript. Allegedly, an easy-to-use language. A way for Web designers and part-time programmers alike, to assemble tools of interactivity, coded right into the markup page.

JavaScript DOM

In an attempt to keep up with the competition, Microsoft reverse-engineered Netscape’s JavaScript, releasing it under the name of Jscript in 1996. Two popular browsers competing for the top spot used somewhat different technologies. Consequently, creating a fully-working website accessible by both browsers was  a true nightmare.

A step in the right direction was the submission of JavaScript to ECMA (European Computer Manufacturers Association) International in November 1996, with the goal of standardizing JavaScript. Thus, a clear path of independent implementation  carved in the digital world.

THE PATTERN IN THE BELT

Throughout the paragraphs above we have mentioned how JavaScript brought a dynamic change to the static-filled internet. Yet, there was no mention by what means it achieved it. Just as an automobile needs fuel to run, so does our scripting language. What little interactivity peaked at the time, functioned through a programming interface, thus allowing the engine’s pistons to do their job.  In came DOM – the limited improvisations of detecting user input and outputting eventful information

JavaScript DOCUMENT OBJECT MODEL

The DOM is an attempt to create a cross-platform and language-independent interface. It forges a connection, between a programming language, in our case JavaScript, and elements of a document – let’s say: an HTML file. Similar to how a family tree looks, a  web page branches our its representation,  in a logical tree form. With that out of the way, a developer now can access different parts of a tree and change their properties, ranging from structure to content. One important property is structural isomorphism which states that should two DOMs implementations be used to create a representation of the same document, the output will be precisely equal in structure: same is true for objects and relationships.

JavaScript DOM

Each entry of the tree is called a node and depending on its position in the tree, relative to other nodes, we can differentiate the following:

  • an element node – the most basic term of any element of the DOM.
  • a root node – just as the name implies, it’s the origin seed from where everything sprouts. In the case of HTML, it’s always HTML node.
  • a child node – a node directly inside another node.
  • a descendant node – Similarly to you not being a child of your grandparents, and yet being one of their descendants, the elements of the DOM are subject to the same logic.
  • a parent node – the opposite of the child node.
  • a sibling node – brothers and sisters of a child node that sit on the same level.

If you want to observe proof of concept, hit the f12 key (developer tools) in any browser and view the current page DOM.

JavaScript DOM

WHAT THE JavaScript DOM IS NOT

As previously mentioned, web-enabled applications are built from marked-up documents. Regardless of the language used to do so (XML, HTML, xHTML), the DOM doesn’t take into account the media content within the file. However, it does care about some of the tags found inside such as: <div></div>, <section></section>, <image>, <p></p> to name a few. For instance, a family tree branch embodies a picture accompanying a small description, usually the date of birth and/or profession. When building the DOM the browser disregards whatever description there is, it only cares about the branch as a whole and assigns a node correspondingly. Therefore, the DOM doesn’t describe objects in XML or HTML files, it describes XML and HTML as objects. 

Creating the DOM is a multi-step process. Once the requested HTML file reaches a computer, the browser will attempt to create a DOM and in the process of doing so loads it up into the RAM. Any changes done through the DOM interface remain in the memory and do not reflect on the source file, just as writing on a copy doesn’t change the original file.

Now that we solved the mystery of what we are working with, let us talk about how a developer goes about changing these particular elements. There are no special actions required to access the DOM. As we have mentioned before, different browsers exhibit different implementations of it, but due to structural isomorphism, you get the same result.

We will avoid getting into various implementation scenarios here. Instead, let’s just graze this subject enough to give you an idea regarding basic DOM procedures.

Accessing the JavaScript DOM

No matter how you organize your JavaScript code, either in the HTML itself or as a separate file, you can immediately use the interface to your liking. Just to give you an idea about a basic format, take a look at this simple implementation:

<code>var element = document.getElementById(id);</code>

Let’s unfurl what exactly is going on here:

var element –  used to declare a variable. In simple terms, this element instructs the computer to reserve memory for a variable called “element”. Think of it as the recordkeeping of a student’s name.

= represents the operation of an assignment, just like the action of actively typing a student’s name under a reserved field, in that school register.

document –  the interface used to access the file itself. It’s important to understand that this interface can’t access content outside its reach. A perfect analogy would be how you can only have your mouse click one thing at a time.  While multiple applications run on your desktop,  only one holds input.

getElementById(id) – a method of the DOM API, used to search a document and return an element equal to the inputted parameter. Now that was a lot of nerdy words. Let’s go back to our car example. In attempting to fetch information about a particular piece of a model, first we would have to search its part number in the registry and to do so, we need the right decimals, or the “id”. Now, access is available to all the data regarding this piece.

JavaScript DOM LEVELS

Just as other elements of the web made technical progress, the “pattern” interface had to provide the required support, hence, it evolved as well. Several levels contributed to maintaining an even ground between elements and scripting possibilities. While they may be obscure, I believe it’s necessary to at least mention this cycle.

  • DOM Level 0 or Legacy – marks the first attempts of modifying a HTML document. There was no standard so might’ve been pretty convoluted to go about it;
  • DOM Level 1 – initiates a set of interfaces aimed at introducing basic functionality when working with marked-up documents (XML & HTML);
  • DOM Level 2 – contains a number of pillars supporting basic operations. It implements accessibility and editing of an object’s style sheet, event handling, as well as an iteration through the logic tree;
  • DOM Level 3 – addresses document validation as well as loading and saving. Elaborates event handling through Keyboard events implementation.

BACK TO THE PRESENT

After that long ride through the defining part of digital history, let’s return to the present. After you’ve had your who, what, and how aperitifs, it’s high noon to elaborate on the benefits JavaScript delivers to programmers and designers alike.

Once again, I’d like to highlight that we are still within the “front-side” layer.

As such, your computer’s browser does most of the horse-work.  Whatever instructions the mastermind creator has designed, will use the resources available on your PC. CPU (central processing unit). GPU (Graphics processing unit). Disk, Network utilization  – are all dedicated to working on the task at hand. Worry not about performance hits, modern computers do millions of tasks within seconds. There is no delay in content delivery since everything is happening on your PC and there is no need to communicate with the server just yet.

After loading a beautiful website with moving contents and interactivity, you might want to sign up for their services. You pull up the registration form, insert a password with special characters and try to go over other fields.

A red field will appear saying you’ve inserted an unaccepted character and require you to type another password. There was no need to send the password to the server for it to be checked if it fits the required parameters. This is a simple example that as a sole won’t affect the performance of a server, but if you scale it up to thousands of users the feedback can be quite devastating.

Therefore, a reduction in data requests results in decreased server load. In a nutshell, that’s how client-server relations work: when server load reaches capacity, services are slowed down for everyone, so reducing the strain indirectly allows for more people to use it.

TO SUM IT UP

So far, we’ve talked about the performance & efficiency side, however, those aren’t the only redeeming qualities. The multiple ways of combining different systems to create your “custom-car” is what JS is about.  From slideshows to fully animated transitions, the possibilities seem endless. You can get a live application that speaks with its user one way or another: data input and validation, event handling, interactive objects enriching your experience as a user at the cost of just a few milliseconds attention span of your computer.

JavaScript and DOM were both a turning point regarding how web-enabled content is displayed. From lines of text to rich user interfaces featuring jaw-dropping effects and functionality, the conversation can last for hours. Unfortunately, it’s time to wrap it up.

Your take-away is the following: JavaScript is an object-oriented programming language, designed as a middleman that enables accessing and editing multimedia content (text, images, videos). DOM is a series of interfaces that act as a bridge between programming language possibilities and HTML document elements. There are multiple levels of DOM each designed to target specific interactivities between certain elements.

Even StackOverflow and GitHub (the two giant places of nerd gathering) implement JS into many of their projects. Should you wish to implement JavaScript into your application, there is a wide array of support and documentation available, which will fit every need.

P.S

One last point to mention is how versatile the language has come to be. Initially developed just as a “belt” for text and image gears, it currently features numerous implementations, branching out of “front-end layer” and heading straight to “server-side scripting” as well as “database layer”. I won’t name the frameworks or framework-like libraries since I will be expecting you to visit our next episode “5 JS Frameworks and Libraries that will serve you well.” Until then, don’t forget to follow our Linkedin, Facebook or Twitter feed, to explore more about who we are, what we do and how we’re bringing development to the next level.