DOM & JavaScript -> The Basics

Introduction

DOM stands for Document Object Model. Unfortunately this name is misleading as Hell. Why you ask? Because the DOM standard does not describe a object model instead it describes an INTERFACE how to access an object model representing an Document.

Honestly, i cannot understand why the committee which ratified this standard has never corrected this mistake but now we have to live with it and keep it in mind when we are talking about the DOM.

JavaScript implemented this interface like many other languages did but in comparison the JavaScript language has it almost deeply integrated as part of the language itself. Of course this statement is false, it is not really part of the language because you do not find the DOM specified in the language standard but the browsers who implements the JavaScript standard automatically add the interface into their implementation so it is always available in the global scope of any JavaScript-file executed from within an browser.

This something I find important to know. All those fance function to manipulate an HTML document are not actually part of the language but are a provided interface to access and to manipulate  such an HTML document.

What is DOM

DOM was created by the W3C and defines a standard way of accessing documents. It is completely platform and language independent  and by that allows for dynamically access and manipulation of the structure, content and style of a document.

It is divided into three parts:

  • Core DOM
  • XML DOM
  • HTML DOM

What we are interested in is the last one the HTML DOM which is supported by most browser nowadays (I would almost go so far to say by every browser).

The HTML DOM defines every HTML element as object,  the properties describing that object as well as methods to change the object and events to interact with the user of such object.

In the context of JavaScript any HTML tag would be represented by an object of the language. By convention the root object in JavaScript is used to be called document. Any other tag which is contained within the root is accessible as property of the object document. Alternatively you could call those properties nodes of the HTML document.

Each node contains a standard set of methods to change itself e.g attaching a new node to itself or deleting a child node.

 

JavaScript DOM Document

 

As already mentioned the root object which contains all other nodes of an HTML document is represented in JavaScript with an object going by the name document. This object literally owns the current active HTML page, a visitor of the  webpage is looking at.

DOM describes several ways to find nodes contained in the root node called in JavaScript document. JavaScript offers the following ways:

Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name

The three methods as you might have already guessed finds you an element. The first one document.getElementById(id) is the most common one. It returns you exactly the one node you were looking for or nothing if not found. Where as the other two might return more than one, exactly one or none.

This is important to keep in mind!!! Little hint look at the method names. The first one is written in singular but the other two are written in plural form “getElementBy… vs getElementsBy…”

Methods are a way to convey information from one developer to other developer. This is true for every programming language!

element.innerHTML =  new html content Change the inner HTML of an element
element.attribute = new value Change the attribute value of an HTML element
element.setAttribute(attribute, value) Change the attribute value of an HTML element
element.style.property = new style Change the style of an HTML element

those four you see represent one of the returned objects from the getElement... category. I believe they are quite self explanatory because they are all just properties except for the element.setAttribute(attribute,value) method.

Attributes of an HTML tag are those “words” you write after the tag but within the pointy brackets <div someAttribute="someValue"></div> nothing really difficult to undestand.

 

document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(element) Replace an HTML element
document.write(text) Write into the HTML output stream

Those five methods enable you to create OR delete certain nodes within your HTML document. Nothing more nothing less

document.getElementById(id).onclick = function(){code} Adding event handler code to an onclick event

This last one here is quite interesting, it lets you associate an callback function with  an certain event, which kind of event you have to specify, if triggered gets then  executed!

 

Property Description DOM
document.anchors Returns all <a> elements that have a name attribute 1
document.applets Returns all <applet> elements (Deprecated in HTML5) 1
document.baseURI Returns the absolute base URI of the document 3
document.body Returns the <body> element 1
document.cookie Returns the document’s cookie 1
document.doctype Returns the document’s doctype 3
document.documentElement Returns the <html> element 3
document.documentMode Returns the mode used by the browser 3
document.documentURI Returns the URI of the document 3
document.domain Returns the domain name of the document server 1
document.domConfig Obsolete. Returns the DOM configuration 3
document.embeds Returns all <embed> elements 3
document.forms Returns all <form> elements 1
document.head Returns the <head> element 3
document.images Returns all <img> elements 1
document.implementation Returns the DOM implementation 3
document.inputEncoding Returns the document’s encoding (character set) 3
document.lastModified Returns the date and time the document was updated 3
document.links Returns all <area> and <a> elements that have a href attribute 1
document.readyState Returns the (loading) status of the document 3
document.referrer Returns the URI of the referrer (the linking document) 1
document.scripts Returns all <script> elements 3
document.strictErrorChecking Returns if error checking is enforced 3
document.title Returns the <title> element 1
document.URL Returns the complete URL of the document 1

The table above describes some given properties every document object contains. They contain all the meta-information and bit more you could need to know to do stuff on your HTML document.

What are the Elements ID/Name/Class?

Let us take a look at the following html document:

getElementByName(name)

The name of any node is the tag name. Means if we request nodes via the document.getElementsbyName(name) and substitute p for name we would receive as answer an array containing two elements! Which you ask? The two we see in our little example HTML document above.

getElementsByClassName(name)

The class name is the value associated to the attribute class. So if we repeat what we did but use now instead ofas name the value content as substitute and change the method to document.ElementsByClassName(name) guess how many elements get we returned?

If you have guessed the Number two you are wrong. The correct answer would be three. And the reason is actually quite obvious. Just count how many nodes have all the class attribute and  then from this set of nodes count how many have the value content? I count three and you ?

getElementByID(id)

The last one. Similar to the previous one it checks the attribute value of the attribute id. But in comparison to the class attribute all IDs must be unique and cannot be shared across nodes. That’s why this method only returns exactly ONE or NO element.

You might ask what happens if your HTML document has through an accident two times the same id somewhere. Well, that depends on your browser. I presume it will simply give you the first one found with the specified ID or if more strict returns nothing. But you need to look that up for the specific browser you want to develop something.

What can we do with Elements?

Well, as you might guess we can somehow manipulate them. What kind of manipulation you want to know? Quite simple: Anything which does not violate the HTML DOM standard.

Lets remember: an element is just one of the children contained within our root node. The root node in HTML is called <html> (what a coincidence XD)and in JavaScript document.

To add e.g textual information we use the property -> innerHtml which every node will have. The innerHtml property represent the “space” between the opening tag and the closing tag of a node in HTML.

if we want to manipulate some kind of attribute we can use the property with the name of that HTML attribute. E.g we want to change the ID from the value ‘#1’ to ‘meh’ we can simply write:

element.id = "meh"; or we use the provided method element.setAttribute("meh")

Of course this assumes that the  object element was correctly initialized with the correct corresponding node! Now to the result:

As you can see the value of the attribute ID has changed! Wonderful, isn’t it? This is true for ANY attribute given to a Node. For instance the style attribute let us tell the browser how to present the node to the user. Via CSS statements we could change the background color, fontsize and a lot more.

But because the style attribute is such an important predefined attribute Javascript gives you a special property to access all these CSS properties:

JavaScript lets you interface with the CSS properties as if the attribute style itself is just a collection of properties bundled within an object. Isn’t that convenient, especially if you have some sort of intellisense and you cannot remember the proper name of an CSS property.

 

Element creation and destruction

What we are missing to cover the basics is how can we create or remove elements of our HTML document.

The methods responsible for this task you already know because you can find them in one of tables you obviously have read very carefully.

document.createElement(element)

This method create a node you can attach to any element you want. How to attach a node i show in a second.

This newly created element is yet not visible. Imagine it as freely living next to your HTML document. It is not yet part of it. To change that we need to attach it to something within our HTML document.

document.appendChild(element)

The appendChild(element) is a special method. Why you ask yourself, certainly not because i wrote it and that is true. It is special because all elements created inherit this method.

As consequence you can not just attach node the root of the document but to any node within that very same document.

Quite simple to expand your document. This logic will stay the same through the whole process of changing your html document. Now let us replace an element we created:

document.replaceChild(element)

This method will, like the appendChild method, be inherited and through that accessible for all nodes.

lets replace our div with a body element:

Tada, we have replaced SomeElement representing a <div></div> with an empty <body></body> tag.

document.removeChild(element)

I’m pretty sure you already know how to use this method but i will show it you anyway. Same rules as with appendChild and replaceChild.

Upps, now our HTML document is without body. I believe we all couldn’t care less, could we?

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *