DOM Manipulation

One of the first roles JavaScript was employed for was manipulating the Document Object Model, aka the DOM. The DOM is a hierarchical, tree-like structure that is generated by the browser as it parses HTML, which is held in memory and used -- in combination with CSS rules -- to generate the visual appearance of the webpage. The DOM is held in-memory by the browser as long as the page is open. If it changes, the browser repositions and redraws the on-page elements to reflect the changes. Thus, by altering the underlying DOM and CSS, JavaScript can be used to alter how a page looks on the fly.

DOM Manipulation with JavaScript

At the heart of manipulating the DOM in JavaScript is the Node - an interface which represents a single node in the DOM tree, and corresponds to many types of specific nodes derive (Not to be confused with Node.js, the server-side implementation of JavaScript). Each node has a number of read-only properties:

It also has methods:

The document

At the top level of the hierarchy is the document, which is the top node of the DOM, as well as metadata about the document (such as document.location, which is the URI of the current document). It is defined as a variable in global scope (but unique to each web page). It has two children -- the head element and the body element, which can be used as starting points when walking the DOM tree. It also maintains lists of anchors, cookies, forms, images, links, scripts, and many other details that can be used to access individual documents.

Creating new Nodes

Nodes are created by the document object, by calling its createElement() method. This takes one parameter, the name of the tag to be created (i.e. “div”). Text is created with the documents’ createTextNode() method, which creates a text node. Created nodes must be added to the DOM with appendChild(), insertBefore(), replaceChild() or similar manipulation method before they will appear in the browser.

Querying the Document

While you can traverse the DOM tree manually to find a particular node of interest, it is far more common to query the document and allow the browser’s (often optimized) internal methods do this for us. These are:

For the querySelector() and querySelectorAll() methods, the selector is a string containing a CSS Selector - one of the same selectors used in a CSS file to identify the elements to apply style properties to.

DOM Manipulation with JQuery

The JQuery library was developed in the 90's to tackle DOM manipulation in a more robust and approachable way. As you can tell from looking at the 'vanilla' JavaScript methods, a lot of typing was invovled. JQuery sought to minimize this by using a single query method, jQuery(). This method is also further abbreviated with the alias $().

The jQuery() function selects a collection of nodes using CSS selectors. In practice, this is very similar to the vanilla javascript querySelectorAll(), with one very important distinction. The results of a jQuery() call is an array-like object called a jQuery.

Manipulating a jQuery Object

The jQuery object includes methods for manipulating the style, value, attributes, and other properties of the nodes it represents, i.e.:

jQuery('a').css('color', 'red');

Will find all anchor tags in the page, and apply a css rule to turn them red (as inline css).

jQuery object methods return a jQuery object, so you can chain multiple calls, i.e.:

jQuery('a').css('color', 'red').attr('href', '');

Changes the href attribute to point to Google as well as turning the tag red. Note also that in JavaScript, chained methods can be written on subsequent lines:

jQuery('a') .css('color', 'red') .css('font-weight', 'bold') .attr('href', '');

This can help keep code legible when chaining method calls.

Alternatively, a jQuery object can be created from a snippet of html:

jQuery("<strong>I'm new!")

It can also be manipulated like any jQuery object:

jQuery("<strong>I'm new!</strong>") .css("color", "blue")

And even added into the DOM:

jQuery("<strong>") .text("I'm new!") .css("color", "blue") .appendTo('a')

Note the two different ways the text "I'm new!" was handled in the above two examples - JQuery is remarkably flexible.

The full jQuery manipulation API is documented (here)[]

JQuery Traversal

The jQuery object can also traverse the DOM tree, i.e.:

jQuery('.foobar') .children('a') .css('color', 'purple')

The first query finds all elements with class foobar, and the children function finds all of thier children that are anchor tags, which are then turned purple.

The JQuery traversal functions parallel those available in vanilla JavaScript, but are typically much less verbose. They also return jQuery objects, which allows them to be chained just like the manipulation methods, and mixing traversing and manipulation is common in JQuery code.

The full traversal API is located here.

Using JQuery

Because JQuery is an external library, it must be included on your page with a <script> tag. You can download it yourself from []( serve it yourself as you would any client-side JavaScript library.

Alternatively, you can set your script tag's src attribute to the appropriate CDN (content delivery network) file at This downloads the file from MaxCDN -- but, if the user has previously downloaded the file from any other website using the same CDN, it is already cached. Since most websites (estimates as large as 97%) use jQuery, it's a good bet that the user will already have it cached. Of course, this means that if the CDN is down, your site won't have its jQuery goodness running...

Finally, you may want to use JQuery's function parameter to delay running your page's code until all embedded files have finished downloading:

jQuery(function(){ // TODO: Code placed here won't be executed // until the page and its dependent files // are completely loaded. })

This is equivalent to listening for the load event on the window:

window.onLoad = function() { // TODO: Code placed here won't be executed // until the page and its dependent files // are completely loaded. }

Normally your JavaScript code is run as soon as it is parsed by the browser. Both of these techniques delay that execution until all the page content has downloaded (including images and script files).