SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    Google Engineer polvero's Avatar
    Join Date
    Oct 2003
    Location
    Mountain View
    Posts
    567
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Thumbs up DOM Scripting Basics

    Hello Sitepointers,
    There are many questions here in the JavaScript forum that essentially allude to similar answers.

    I am going to start a 'multi-part series' thread for those who are new to JavaScript or still getting their feet wet. The following posts will specifically outline introductory concepts and be targeted toward web developers who are missing the third piece of the trinity (JavaScript). Those three pieces being (X)HTML (content & markup), CSS (Presentation / Look & Feel), and DOM Scripting using JavaScript (Behavior / Interaction).

    Therefore, if you're already knee deep in HTML and CSS, and you want to jump to the next level, this will be perfect for you.

    These teachings are considered "Introductory" and should be treated as such.

    =============================================

    Targeting an element
    In this example we will use a portion of markup as our base content.
    Code:
    <div id="example">
      <h2>Sample Header</h2>
      <ul>
    	<li>list item one</li>
    	<li>list item two</li>
    	<li>list item three</li>
      </ul>
    </div>
    CSS
    In CSS, if we wanted to target the element that has an id of "example" - our style rule would look like this:
    Code:
    #example {
      /* my properties here */
    }
    Of course if we wanted to target the <h2> element within the container that has an id of "example" - our style rule would look like this:
    Code:
    #example h2 {
      /* my properties here */
    }
    Wonderful. That was easy wasn't it
    JavaScript
    In JavaScript we have similar methods of obtaining an element. Although the syntax is a bit different, you'll find that it makes a bit more sense to "speak out loud" as to which elements you want to target.

    Let's first start off by targeting an element with an id of "example". Here's how it would look in JavaScript
    Code:
    document.getElementById('example');
    At first glance you might be wondering what 'document' is. In this case 'document' is our outer root node (even above the <html> element). As you also might have noticed, we used a built-in DOM method called "getElementById." And as you can see, it does exactly what we wanted it to.

    The method "getElementById" always requires that you put a parent element in front of it. In our example we used "document." In any case, however, it is pretty much safe at all times to use "document," meaning you shouldn't ever have to worry about using something else besides "document."

    Targeting the h2 element
    Of course you might be wondering how we're going to get our <h2> element within our snippet of HTML. One simple way we can achieve this is to add an id to our <h2> as follows:
    Code:
    <div id="example">
      <h2 id="sample-header">Sample Header</h2>
      <ul>
    	<li>list item one</li>
    	<li>list item two</li>
    	<li>list item three</li>
      </ul>
    </div>
    Since we are already familiar with our "getElementById" method, we can use that as shown below:
    Code:
    document.getElementById('sample-header');
    Variable assignment and referencing
    In programming languages (like JavaScript), variable assignment is key. In this next demonstration we will assign our reference to an element to a variable in JavaScript.
    Code:
    var el = document.getElementById('example');
    Here we have assigned a reference of the element with id of "example" to a variable called "el." This must be understood before we move on.

    Coming up Next: arrays & "getElementsByTagName"
    In the next post we will learn how to target multiple elements. Stay tuned.

  2. #2
    Google Engineer polvero's Avatar
    Join Date
    Oct 2003
    Location
    Mountain View
    Posts
    567
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Part II: Arrays & "getElementsByTagName"

    Arrays & "getElementsByTagName"
    In this section you will learn about writing arrays in JavaScript and how they apply to HTMLElement Collections. An HTMLElement collection is an array storage of html elements.
    Arrays
    An array in any programming language is generally a collection of things. It rarely makes sense to have an array of just one item.

    In JavaScript we can create an empty array stack as follows:
    Code:
    var test_array = [];
    We can in fact confirm that this is an array but doing such:
    Code:
    var test_array = [];
    alert(test_array.constructor == Array);
    // This should alert "true"
    Of course, an empty array doesn't do us any good. But we do indeed know that we have an array. To populate an array, we would write the following:
    Code:
    var test_array = ['item1', 'foo', 'bar'];
    We can check how many items are stored in our array by referencing its length property:
    Code:
    alert(test_array.length);
    You should see the number '3'. Wonderful!
    Accessing members of an Array
    In any given array, each item has a key. Consider the fact that the only way you can get access to these items is with their key much in the same manner that you have access to your home is through a door with a lock that requires a key. These keys are automatically given to you by an index number. The first key to obtain the value of your first item is '0' (zero).

    There are two ways of using your key to access members of an array. First and foremost is to use the "subscript" notation. Using subscript notation, we will access the first member of our test_array.
    Code:
    var test_array = ['hello', 'world', 'foo'];
    var a = test_array[0];
    alert(a);
    This can also be achieved using the build-in JavaScript method called "item." That is done as follows:
    Code:
    var test_array = ['hellow', 'world', 'foo'];
    var a = test_array.item(0);
    alert(a);
    Notice in both cases that we used '0' to access our first item. Knowing that, if we wanted to get access to our third member of the test_array variable, we would use the number '2'. If you're wondering which notation to use, I generally prefer subscript notation when accessing members of arrays because it's shorter. You are free to use which ever one you want.

    Exercise
    Take the following array into consideration:
    Code:
    var shows = ['south park', 'star trek', 'family guy', 'american dad', 'Lucy', 'Robot Chicken'];
    • What is the key index number to 'Lucy'?
    • How can I determine the value of "third from the last" item in the people array?
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    .
    Nevermind that this is a poor-man's quiz. This is the best way I can hide the answer from you. If you did in-fact try to figure out the questions on your own - good for you. Here is some valuable information about the answers:
    The index number to access 'Lucy' in the 'shows' array would be '4'. Since 'Lucy' is our fifth member in the array, we need to subtract one (-1) from where he stands in our list.

    Moving on, we will not assume that we will always know that there are six members of our 'shows' array (Just like we don't always want to assume that there are going to be a set number of list items <li> in any given unordered list <ul>). Using the 'length' property on the array, we can have the total number of members. Then from that point we can subtract from that number and get our "third from the last." See the following demonstration:
    Code:
    var shows = ['south park', 'star trek', 'family guy', 'american dad', 'Lucy', 'Robot Chicken'];
    var total_shows = shows.length;
    var third_from_last = total_shows - 3;
    alert(shows[third_from_last]);
    You should see "family guy" if this was done correctly (good show btw )

    getElementsByTagName
    Using JavaScript, there are virtually two ways you can access elements in a DOM. You can grab a single element (with getElementById) or a collection of elements (getElementsByTagName (think 'array'). If you are unfamiliar with the term DOM (Document Object Model) or have heard it before but don't know what it means, a DOM is an element tree. In short terms, it is a collection of nodes that has family-like relationships. This is nor the time or place to talk about quirky browser implementations on how the DOM "should behave," but here is how the DOM would be represented according to our base HTML from our primary post.

    Here is the HTML represented again for your convenience:

    Code:
    <div id="example">
      <h2>DOM Scripting Basics</h2>
      <ul>
    	<li>list item one</li>
    	<li>list item two</li>
    	<li>list item three</li>
      </ul>
    </div>
    The DOM for this snippet may look more or less like the following in your browser memory:
    Code:
    #document
      HTML
    	HEAD
    	  TITLE #text
    	BODY
    	  DIV
    		H2 #text
    		UL
    		  LI #text
    		  LI #text
    		  LI #text
    For the scope of this lesson, don't worry too much if this DOM stuff doesn't make much sense to you. The matter at hand is grabbing an HTMLElement Collection using 'getElementsByTagName' (note the plural). Similar to getElementById, we will need to start with a root element. Unlike getElementById, we will most rarely want to start with 'document' as the root. Instead we will want a more specific root (or parent) element so that we don't target everything in the entire document. It may cause unexpected results and in many cases can be a performance issue. However, nevermind that now.

    Let's revisit an exercise from the first lesson. Say we want to target the h2 element inside an element that has an id of 'main.' If you remember correctly, we can do that in CSS as follows:
    Code:
    #example h2 {
      /* my properties here */
    }
    If you also remember correctly, we were able to do this in JavaScript with 'getElementById' and modifying our HTML. However, let's avoid touching our markup - as we are pretty happy with it "as it is." What we want to try and do is target that specific element without adding an extra id attribute. Take a look at the following:
    Code:
    var el = document.getElementById('example');
    var header_collection = el.getElementsByTagName('h2');
    In this case we have an array with one item. What this means is that 'getElementsByTagName' returns an array.

    Take special note that we first obtained an element (the div tag with an id of 'example'), and then used that as the parent node reference.

    Accessing the first element in our array
    If memory serves us correctly, we should be able to access the first element in our array stack using a number key. In this case, to target our h2 element, we can do the following:
    Code:
    var el = document.getElementById('example');
    var header_elements = el.getElementsByTagName('h2');
    var my_header = header_elements[0];
    By now we should have just enough information to target any element in the DOM we want
    Coming up Next: Dynamic Styling and loops
    In the next post we will learn how to dynamically change the style of an element, append class names, and learn how to loop through entire element collections. Stay tuned!
    Last edited by polvero; Dec 3, 2007 at 16:27.

  3. #3
    Git-R-Done
    Join Date
    Nov 2001
    Posts
    1,194
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Great stuff. Please keep it coming!
    John Saunders

  4. #4
    SitePoint Member
    Join Date
    Jul 2007
    Location
    Dallas, TX
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I tried to use this tutorial to create a quiz...my first javascript...and I no doubt messed it all up. Maybe you could look at my code and tell where I went wrong? It actually works in Safari but I really need it to work in Firefox and IE.

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Untitled Document</title>
    <style type="text/css">
    <!--
    </style>
    </head>
    <body>
    <form id="form1" name="form1">
    <p id="1" style="font-family:Arial, Helvetica, sans-serif; font-size:12px; background-color:#FFFFFF;">
    TEST 1<br />
    <input type="radio" name="RadioGroup1" value="hair1" id="RadioGroup1_0" />
    Radio 1<br />
    <input type="radio" name="RadioGroup1" value="hair2" id="RadioGroup1_1" />
    Radio 2<br />
    <input type="radio" name="RadioGroup1" value="hair3" id="RadioGroup1_2" />
    Radio 3<br />
    </p>
    <p id="2" style="font-family:Arial, Helvetica, sans-serif; font-size:12px; background-color:#FFFFFF;">
    TEST 2<br />
    <input type="radio" name="RadioGroup2" value="skin1" id="RadioGroup2_0" />
    Radio 1<br />
    <input type="radio" name="RadioGroup2" value="skin2" id="RadioGroup2_1" />
    Radio 2<br />
    <input type="radio" name="RadioGroup2" value="skin3" id="RadioGroup2_2" />
    Radio 3.<br />
    </p>
    <p id="3" style="font-family:Arial, Helvetica, sans-serif; font-size:12px; background-color:#FFFFFF;">
    TEST 3<br />
    <input type="radio" name="RadioGroup3" value="build1" id="RadioGroup3_0" />
    Radio 1<br />
    <input type="radio" name="RadioGroup3" value="build2" id="RadioGroup3_1" />
    Radio 2<br />
    <input type="radio" name="RadioGroup3" value="build3" id="RadioGroup3_2" />
    Radio 3<br />
    </p>
    <input type="button" name="button1" value="submit" onclick="showScore()" />
    </form>
    <script type="text/javascript">
    var array1=newArray();
    function move1() {
    document.location = 'http://www.personalalchemy.com/dosha_vata.html';
    }
    function move2() {
    document.location = 'http://www.personalalchemy.com/dosha_pitta.html';
    }
    function move3() {
    document.location = 'http://www.personalalchemy.com/dosha_kapha.html';
    }
    function move4() {
    document.location = 'http://www.personalalchemy.com/dosha_tri.html';
    }

    function showScore(){

    array1[0]=0;
    array1[1]=0;
    array1[2]=0;
    test=0;
    testv=0;
    test2=9;

    for (i=1;i<4;i++){
    var temp = document.getElementById (i);
    var inputs = temp.getElementsByTagName ('input');
    for (ii=0;ii<3;ii++){
    if (inputs[ii].checked){
    array1[ii]++;
    if(array1[ii]>testv){
    test=ii;
    testv=array1[ii];
    test2=9;
    }else if(array1[ii]==testv){
    test2=array1[ii];
    }
    }
    }
    }
    if (test2!=9){
    move4();
    }else if (test==0){
    move1();
    }else if (test==1){
    move2();
    }else if (test==2){
    move3();
    }
    }

    </script>
    </body>
    </html>

  5. #5
    SitePoint Member
    Join Date
    Jul 2007
    Location
    Dallas, TX
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks I figured it out...was a bug in my code. Thanks for the help!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •