No more GetElementbyID

Here’s a simple script:

<div id=”‘hello’”>Hello World. </div>

<script type=”‘text/javascript’”>

var test=document.getElementById(‘hello’);

test.appendChild(document.createTextNode(‘Goodbye World’));
</script>

This is your basic example of DOM manipulation. You create a variable and start manipulating the document based on that element. But here’s something I bet you didn’t know. That first line is not needed:

<div id=”‘hello2′”>Hello World. </div>

<script type=”‘text/javascript’”>
hello2.appendChild(document.createTextNode(‘Goodbye World’));
</script>

Anytime you create an element with an ID a variable with the same name is automatically available for you to use.

(Update: After some explorations it turns out that although this does sometimes work it’s unreliable in strict mode. It’s probably not recommended for general use)

Post to Twitter

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>