Support Forums

Full Version: Javascript and the DOM
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Sorry if this is in the wrong section, however there is no Javascript section.

Hello, in this tutorial im going to be covering how to manipulate your web page using Javascript and a powerful mechanism called the Document Object Model. The contents of your webpage are available through the DOM, and can be manipulated and changed. In this tutorial we will be manipulating the DOM with Javascript.

This tutorial will not teach the basics of Javascript, if you would like a tutorial on learning Javascript I recommend,
http://w3schools.com/js/default.asp

The DOM has a special set of variables and objects that represent different aspects of the webpage such as content, location, status and many more.

Common DOM Objects
  • document - Represents the (X)HTML page
  • location - Represents the current URL
  • status - Represents the browser's status bar
  • history - Represents the browser's history
  • navigator - Represents information about the browser
You can find all DOM objects on this page,
http://www.w3schools.com/jsref/obj_window.asp


You can allow Javascript to manipulate the DOM. We are going to start with a simple example of changing the style of a page;
PHP Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<
html>
    <
head>
        <
meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <
title>Simple DOM Manipulation</title>
    </
head>
    <
body>
        <
h1>Wat u want foo</h1>
        <
script type="text/javascript">
            
// Javascript will change the style of the page without CSS
            
document.body.style.color "green";
            
document.body.style.backgroundColor "blue";
            
document.body.style.textAlign "center";
        </
script>
        <
p>lol</p>
    </
body>
</
html

There are some subtle differences in this snippet;
  1. The script is placed in the body tag. The reason this is placed in the body tag is because it refers to the body on the fly, and I cant place it in the header because while the page is loading, the script will run when there is no body.
  2. There is no CSS. As you can see, there is absolutely no CSS here.
  3. The DOM is used to change the page. The syntax goes all the way from the document to the body itself, to its style attributes and finally to its different attributes such as background color and aligning.
  4. The document represents the actual page.
  5. The body represents the <body> tag.
  6. The style represents the style of the previous object. In this case, the <body> tag.
If your familiar with CSS you may notice something slightly different. All the attributes are named the same, except slightly different. In CSS, attributes such as font-weight or background-color use dashes to seperate words, while the DOM uses capitalization such as fontWeight and backgroundColor instead.


Of course, you can also accomplish this task with events. In this next example, im going to show you how to use button events to edit the DOM using javascript functions.
PHP Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<
html>
  <
head>
    <
title>Manipulating the DOM through Button Events</title>
    <
meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <
script type="text/javascript">
 
        function 
changeColors(colorbgcolor) {
            
document.body.style.color color;
            
document.body.style.backgroundColor bgcolor;
        }
 
    </
script>
  </
head>
  <
body>
      <
h1>Edit the DOM through button events and Javascript</h1>
      <
fieldset>
          <
input type="button" onclick="changeColors('black', 'white')"
                 
value="Black and White" />
          <
input type="button" onclick="changeColors('green', 'blue')"
                 
value="Green and Blue" />
      </
fieldset>
  </
body>
</
html
  1. A button event calls a function which edits the DOM. A javascript function edits the DOM. A button is used to call this function.
  2. Embedding quotes within quotes. Take a look at the onclick lines, you will notice the function parameters are enclosed in single quotes ('). This is the case because if double quotes where used as usual, the browser would nest the quotes as "changeColors(" and white")".
  3. Script is placed in the head. Now that the script isnt used immediately when the page loads, the script is instead placed in the <head> tag.
Thats some basic DOM manipulation. The DOM isnt just limited to editting the styles of pages, it can do many other things.

Next, we are going to manipulate forms and different types of input using the getElementById() function from the document object. In order to use this function, you must specify an id for the element you want to modify. Here is a simple script which takes a specified name from one input field, and prints out a sentance in another.
PHP Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<
html>
  <
head>
    <
title>Manipulating the DOM through Button Events</title>
    <
meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <
script type="text/javascript">
 
        function 
submit() {
            var 
name document.getElementById("name").value;
            var 
output document.getElementById("output");
            
output.value "Hello " name "!";
        }
 
    </
script>
  </
head>
  <
body>
      <
label for="name">Name: </label>
      <
input type="text" id="name" />
      <
br />
      <
input type="button" id="name" value="Submit"
             
style="width:10%" onclick="submit()" />
      <
br />
      <
label for="output">Output: </label>
      <
input type="text" id="output" />
  </
body>
</
html
  1. The submit button outputs the data. The submit() function uses two variables: name and output. The getElementById() function references the textfield with the specified id and the value property holds the data inside the textfield.
  2. Both textfields have an id. Both textfields hold an id, in order to use the getElementById() function, there must always be an id assosciated with the element the function will reference.
Thats useful and all, but what if we want to actually edit a page? A textbox isnt the best way to output data. So instead, I introduce to you the innerHTML property. This property describes the HTML data in an element. Take a look at this example;
PHP Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<
html>
  <
head>
    <
title>Using innerHTML</title>
    <
meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <
script type="text/javascript">
 
        function 
submit() {
            var 
name document.getElementById("name").value;
            var 
output document.getElementById("output");
            
output.innerHTML "<em>" name "</em>";
            
output.innerHTML += ", welcome to the site!";
        }
 
    </
script>
  </
head>
  <
body>
      <
fieldset>
        <
label for="name">Name: </label>
        <
input type="text" id="name" />
        <
br />
        <
input type="button" id="name" value="Submit"
            
style="width:10%" onclick="submit()" />
      </
fieldset>
      <
br />
      <
div id="output">
      </
div>
  </
body>
</
html
  1. Validators get confused by forward slashes. When you want to use a / in javascript strings, you must proceede it with a backslash.
When dealing with input elements such as a list box, you need to create a variable and use the getElementById() function as usual then loop through the lists contents. Use the selected property (boolean) to determine whether or not a list item is selected. The checked property will determine whether or not a checkbox is checked.

Radio buttons are quite different. They require a new attribute and manipulating the DOM is slightly different. In order to interpret radio buttons, you would use the getElementsByName() function and the name attribute.
PHP Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<
html>
  <
head>
    <
title>Manipulating the DOM through Button Events</title>
    <
meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <
script type="text/javascript">
 
        function 
submit() {
            var 
part1 document.getElementsByName("part1");
            var 
part2 document.getElementsByName("part2");
 
            for (
0part1.lengthi++) {
                var 
name part1;
                if (
name.checked)
                    var 
selectedName name.value;
            }
 
            for (
0part2.lengthi++) {
                var 
name part2;
                if (
name.checked)
                    var 
selectedName2 name.value;
            }
            var 
output document.getElementById("output");
            var 
outputText selectedName selectedName2;
            
output.innerHTML outputText;
        }
 
    </
script>
  </
head>
  <
body>
      <
h1>Match the proper names...</h1>
      <
fieldset>
        <
input type="radio" name="part1" id="rune" value="Rune" />
        <
label for="rune">Rune</label>
 
        <
input type="radio" name="part1" id="tune" value="Tune" />
        <
label for="tune">Tune</label>
 
        <
input type="radio" name="part1" id="dune" value="Dune" />
        <
label for="dune">Dune</label>
 
        <
br /><br />
 
        <
input type="radio" name="part2" id="mocus" value="Mocus" />
        <
label for="mocus">Mocus</label>
 
        <
input type="radio" name="part2" id="focus" value="Focus" />
        <
label for="tune">Focus</label>
 
        <
input type="radio" name="part2" id="locus" value="Locus" />
        <
label for="dune">Locus</label>
      </
fieldset>
        <
br />
        <
input type="button" id="name" value="Submit"
            
style="width:10%" onclick="submit()" />
      <
br />
      <
br />
      <
div id="output">
 
      </
div>
  </
body>
</
html
  1. The getElementsByName() function returns an array of all radio buttons in a group. This function returned an array of 3 values (the size of all the options).
  2. All choices are iterated. All radio buttons are iterated through, and the if statement checks whether the button is selcted. If so, a new variable is made to hold the value of that button.
  3. Finally, the output div holds the two values. Both values from the two radio buttons are concatenated and are printed out using the innerHTML property.
  4. The name attribute is used for each radio button. This is used to distinguish between the two different radio button groups.
Thanks for reading my tutorial on basic manipulation on the DOM with Javascript, if you have any questions please message me here. Cool
I had a go at this.

and was lost.

Sad
Im sorry to hear. Sad
No worries though, learning about the DOM is just getting to know the underlying mechanism that build web pages, so of course its not required but a nice thing to know. Smile
This seems to be very well written, I know the basics of Javascript so I only read through the snippets since I knew what they would mean and it seems you did a good part covering the GetElementById tag which is very useful ;)
Thanks for the feedback. Smile
This is actually the first time I have written a tutorial in such a format, and I see its effective so I will continue doing so. If you need a tutorial on something, just ask.
It's a nice tutorial but jquery just makes this kinda stuff pointless Smile
It does, but there are always the odd number of people who dont use it.