Wednesday, 9 December 2015

What is the DOM in Javascript/jquery ?

          The DOM is basically an API you use to interface the document with, and is available in many languages as a library ( JS is one of those languages ). The browser converts all the HTML in your web page to a tree based on the nesting. Pop open Firebug and look at the HTML structure. That is the tree I'm talking about.

If you want to change any HTML you can interact with the DOM API in order to do so.

<html>
 <head><script src="Tempfile.js"></script></head>
 <body>blah</body>
</html>
In Tempfile.js I can reference the body using:

onload = function() {
    document.getElementsByTagName('body')[0].style.display='none';
}
The getElementsByTagName is a method of the document object. I am manipulating the body element, which is a DOM element. If I wanted to traverse and find say, a span I can do this:

onload = function() {
 var els = document.getElementsByTagName('*');
 for ( var i = els.length; i--; ) {
    if ( els[i].nodeType == 1 && els[i].nodeName.toLowerCase() == 'span' ) {
       alert( els[i] )
    }
 }
}
I am traversing the nodeList given back by getElementsByTagName in the snippet above, and looking for a span based on the nodeName property.

No comments:

Post a Comment