Home No more GetElementbyID
Post
Cancel

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)

This post is licensed under CC BY 4.0 by the author.