February 01, 2023, 04:20:29 am
Welcome, Guest. Please login or register.

Login with username, password and session length
News: Welcome to Revolution X, where Coding meets Graphics.
  Home Help Search Arcade Affiliates Staff List Calendar Members Login Register  

Tutorial #3: Simple DOM Methods

Pages: [1]   Go Down
Author Topic: Tutorial #3: Simple DOM Methods  (Read 264 times)
Agent Moose
Offline Offline

Gender: Male
Posts: 1,470

View Profile WWW
Badges: (View All)
« 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:

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

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

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:
var the_div = document.getElementsByTagName("h1");

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

the_tag.innerHTML = "";
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:
var the_tag = document.getElementsByTagName("h1");

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

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:
var the_id = document.getElementByid("the_div");

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:
var the_id = document.getElementById("the_div");
the_id.childNode.innerHTML = "RAWR";
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.
Report Spam   Logged

Share on Facebook Share on Twitter

Pages: [1]   Go Up
Jump to:  

Powered by EzPortal
Bookmark this site! | Upgrade This Forum
SMF For Free - Create your own Forum

Powered by SMF | SMF © 2016, Simple Machines
Privacy Policy