Revolution X

Coding Community => Tutorials => Topic started by: Agent Moose on May 27, 2009, 07:14:04 am



Title: Tutorial #3: Simple DOM Methods
Post by: Agent Moose on May 27, 2009, 07:14:04 am
With DOM (Document Object Model) you can restructure an entire HTML document. You can add, remove, change, or reorder items on a page.

In DOM, you can use two methods of grabbing an element:
-getElementsByTagName()
-getElementbyId()

I will be using this HTML as the example:
Code:
<html>
<head>
<title>DOM Tutorial</title>
</head>
<body>
<h1>Header</h1>
<p>Hello world!</p>
<div id="my_div">This <b>Text</b> is in a div.</div>
</body>
</html>

First, you must put whichever method you want to use into an array:
Code:
<script>
var the_tag = document.getElementsByTagName();
</script>

Inside the Parentheses you would put the ID or the Tag of the element you want to alter, in this case, it will be the Tag Name:
Code:
<script>
var the_div = document.getElementsByTagName("h1");
</script>

Now, to alter that text inside the H1 tag,you would do this:
Code:
<script>
var the_tag = document.getElementsByTagName("h1");

the_tag.innerHTML = "";
</script>
In that code, I have changed the text in the h1, which is "Header" to nothing.  If you wanted to add more text to it, so it will keep the text already in it, you can do this:
Code:
<script>
var the_tag = document.getElementsByTagName("h1");

the_tag.innerHTML += "<br>This is the Text";
</script>

If you just have an equal sign (=) it will change all the text in that one tag to the text you want it to be.  If you have a plus, then an equal sign (+=) it will add text into that element specified.

Here is an example of getting an element by its ID:
Code:
<script>
var the_id = document.getElementByid("the_div");
</script>

With that, you can change the HTML just like I showed you above.  But, what if you only wanted to change the bold text?  Well you can, there are two ways.

You can either do the getElementsByTagName() or, you can do it this way:
Code:
<script>
var the_id = document.getElementById("the_div");
the_id.childNode.innerHTML = "RAWR";
</script>
That would get the childNode (the bold tag) text and change it to the word "RAWR".

Just a side note:
 - When your getting an ID, the method used would be getElementById(), since there is only one ID with that name, there wouldn't be an "s" in there.
 - If your geting a tag, the method you would use would be getElementsByTagName() because there will be more than one element with that tag name, meaning, you would need the "s" in there.