TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Javascript, AJAX, E4X (http://www.talkphp.com/javascript-ajax-e4x/)
-   -   Part 1: Getting Started with Javascript and DOM (http://www.talkphp.com/javascript-ajax-e4x/1395-part-1-getting-started-javascript-dom.html)

Wildhoney 11-06-2007 06:47 PM

Part 1: Getting Started with Javascript and DOM
 
1 Attachment(s)
Before we begin, perhaps 2 terms you're not familiar with that you will see thrown around a lot. Prototype is an extremely popular Javascript framework that is quite frankly, truly awesome, and although we won't be using it in this article, Karl will be along shortly with a guide on how to do it in Prototype - so you can compare. Whilst DOM on the other hand, is the document object model, it's essentially a way at looking HTML nodes as objects with properties.

I find Javascript is one of those languages that every man and his dog has heard about, but not many people (or dogs) know how to use it very well. I remember being one of those individuals a couple of years ago - I do admit it! After all, we all have to begin somewhere. One of the most tricky parts to Javascript is that FF and IE have their own ways of doing things, but since W3C stepped in, things have settled down and we've been heading towards a place where everything is standardised, of course there are still some exceptions such as the dynamic setting of enctype in Internet Explorer.

Let's take the following HTML block:

Code:

<div id="myContainer">
        <div>Change me</div>
        <div>Modify me</div>
        <div>Alter me</div>
</div>

Suppose we wanted to change (modify and alter) the 3 DIVs. None of the child nodes of myContainer have any properties (id or class, for instance) so we cannot reference them directly. Whereas the parent node, which is myContainer, does. Take a look at the following code:

javascript Code:
var pContainer = document.getElementById('myContainer');

It may be wise to point out that var is much like PHP's public, private and protected. It's a way to initialise variables. pContainer is now a reference to our parent DIV object.

The following 2 if statements may seem a little peculiar, however, in Javascript we must check to see if something exists or has properties, else we will be overwhelmed with Javascript errors if something goes wrong. Squidoo, for instance, has a myriad of Javascript errors I noticed yesterday. They could quite easily be prevented but it's down to nothing more or less than bad programming techniques. Squidoo, in my personal opinion, is a terrible site as well (blasphemy?)

javascript Code:
if(!pContainer)
{
    return;
}

if(!pContainer.hasChildNodes)
{
    return;
}

The first if statement states that if pContainer does not exist then return. The second if statement is saying if pContainer has no child nodes - where in our case it does, it has 3, or in Internet Explorer's case sometimes 6, then return.

Coming back to the previous statement made about Internet Explorer. Sometimes IE will render #text elements between the DIV nodes and thus giving us 6 child nodes. This, however, can be easily thwarted as you will see later on.

The next line in our code is the starting of our loop to weed out all the child DIVs:

javascript Code:
for(iIndex = 0; iIndex <= pContainer.childNodes.length; iIndex++)

The above code says that the for loop should loop for as long as iIndex does not exceed the amount of child nodes in pContainer. And so the loop begins! Dizzy yet?

javascript Code:
var pDiv = pContainer.childNodes[iIndex];

We then subsequently assign the object of the first child node found to pDiv. We are assuming that it is a DIV here, perhaps a more apt name would be pTarget or pObject, but I'm confident in my own abilities to only obtain DIVs!

Next is the code to put any end to Internet Explorer's futile plans to slip through any #text objects.

javascript Code:
if(pDiv.nodeName.toLowerCase() != 'div')
{
    continue;
}

What we're effectively saying here is that if the node name of our child node is not a DIV then loop again until we do find a DIV. That way no actions are performed on a #text object causing us a nasty error. Pesky Internet Explorer, I tell thee!

Last but not least, once we're satisfied that all we have is a DIV, we can modify its inner HTML to contain whatever we want it to contain. I'll choose, shall I? Let's put in there: I've Changed. Fear not, our DIVs haven't turned over a new leaf while been looping - loops in Javascript aren't that slow.

javascript Code:
pDiv.innerHTML = "I've changed";

The difference between innerHTML and value, that you may have seen elsewhere, is that innerHTML would work for elements that have their text outside of the object. Like in our case:

Code:

<div>Alter me</div>
But with value the element would have to be like so:

Code:

<input type="text" value="Get Me!" />
Well, I do hope you've learned 1 or 2 things. Traversing the HTML DOM is not really the most difficult task as you see. But if someone were to simply paste all that code to you then it may look difficult, admittedly. Just to finish off I have attached the HTML document I was working with for you to take closer look! Run it in your browser, rip it apart, do whatever you will, I won't be upset!

Nor 11-06-2007 07:08 PM

Good stuff, DOM is one of the easiest things in Javascript imho. I do regret 1 1/2 years of InvisionFree coding...Freelancing is funner :).

hostfreak 11-06-2007 11:09 PM

Great read. I'm sure it will help many of new comers to JS; wouldn't even hurt veterans to read. Looking forward to Karls addition.

Side note, I love the quality of articles posted here.

Wildhoney 11-06-2007 11:35 PM

Thanks a lot, hostfreak :) It's much appreciated! Plenty more to come.

maZtah 11-06-2007 11:55 PM

Great article indeed! Very useful, also as a reference!

The Avangelist 11-08-2007 09:26 AM

Have I missed something
 
I know it's early and I haven't had any tea yet but I feel like I skipped a bit?

What relevance does this have to a real world situation? I now know how to enter a line of code to stop ie from bastardising my commands, but what else have I been shown?

Toooo early.....

Karl 11-08-2007 12:52 PM

You've been shown how to manipulate DOM elements using JavaScript. More specifically, how to access an element by its ID and then perform a common task on its child nodes.

As for relevance to the real world, apply your own situations.


All times are GMT. The time now is 11:49 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0