|
Helping ordinary people create extraordinary websites! |
JavaScript getElementByIdJavaScript document.getElementById DOM ScriptingDOM scripting, or Document Object Model scripting, is one of the most powerful areas of JavaScript. Through DOM scripting, you can manipulate the content of the page through pure JavaScript, opening up infinite possibilities for dynamic, interactive web pages. The core of DOM scripting, and the best entry point, is document.getElementById(). Introduction HTML nodesAt this point in our tutorial, HTML knowledge is important, however we will try to explain examples as we go along. If you think your HTML might not quite be up to scratch, we have a great HTML Tutorial you may find handy for this section. A HTML node, entity, or element (for our purposes, they are roughly
equal terms), refers to the virtual object the browser creates for a
particular HTML tag. All HTML tags are nodes, and most have an <div id="someid"></div> When building complex HTML interfaces, most of your key elements should be given IDs, as this is the most common (and simplest) way to access the node programmatically, or from within your programming code. Accessing nodes programmaticallyThe web browser will expose the virtual object for each node to JavaScript - in other words, it will give your JavaScript code access to (and control over) every HTML node on the page. And you do this by acquiring a handle on the node - think of a handle like a way to work with an object, just as you would in the real world.
In this example, we call the <div id="someid"></div> While actually examining the result of this code is slightly complicated, it does in fact change the ID of the <div id="someid"></div> Run it in your browser - that's right, you just changed the content
of your page through JavaScript, and dynamically too. Play around with
this example; you can, of course, use HTML in the And there you go: Hello World, first with JavaScript, now with DOM scripting. A note on object chainingLet's take a quick look back at our example:
Here, we first take
This is exactly the same, because of chaining. Chaining simply refers to adding more and more methods/properties onto the end of your instruction, because each returns an object value. The moment you have an object in some kind of variable/function/property/method, you can probably use dot notation to continue the statement in the same line of code. If a function returns an object, you can continue working with it without having to take that object and put it into another variable first. However, you can't work on multiple properties of a DOM node in a
single call, as the property itself is not an object (and hence cannot
be continued with dot notation). Also, it takes some time, especially
on large pages, to call
|
|