HTML Nodes & Node Types

Taken from my blog:

So today I was going through Jquery’s source code. I noticed that they use a lot of node types and names, and I wasn’t really sure what these methods and properties were. Now, I already knew DOM elements were made of nodes and that some Javascript DOM queries returned node lists, but frankly I didn’t know much else other than that. So I decided to dig into the topic, and here’s what I found. Hopefully it’s of use to you.

What are Nodes?

Simply put, nodes are data types that link objects(data) together. Here’s a quick Javascript code example:

function Node(data){
this.data;
this.next = null;
}
var a = new Node("a"); //a.next is null..not linked to anything
var b = new Node("b"); //b.next is null..not linked to anything
a.next = b; //a is now linked to b throught the next property

So can you see how this is similar to html? Look at this one:

function Node(name){
this.data;
this.child;
this.parent;
this.siblings;
}

Obviously you would need many algorithms to make sure all these are linked the right way when you add them, but you get the idea behind the data type! These nodes really aren’t that complicated. They’re just data that are linked to other data…through their properties!

Html Node Types

“Every object in html is a node”

Boom! Did you know that?

Knowing that, the way html works behind the scenes becomes a little bit easier to understand.

Although they are all basically nodes, they all have different types assigned to them. Here’s a list with W3C’s specifications. You’ll most likely be interacting with 1–3 for the most part.

These values are accessible with Javascript via nodeType. Here’s a snippet example:

//add a paragraph with id "para" in the HTML
var para = document.getElementById("para");
//You should get a 1 because this is an element type
var nodeType = para.nodeType;

There’s another property that might come in handy called nodeName, which returns an upper case string containing the name of an element node. You access that property like this:

//add a paragraph with id "para" in the HTML
var para = document.getElementById("para");
//You should get a 1 because this is an element type
var nodeType = para.nodeName; //"P"

Quick challenge

Given all this information it should be pretty easy to understand what’s going on inside this jQuery function. Can you decipher it? Thanks for reading!

nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},