Forum Moderators: open

Message Too Old, No Replies

Is this any good?

tiny .getElementById function..

         

Fiasst

6:56 pm on Nov 28, 2007 (gmt 0)

10+ Year Member



Hey, I just had a thought about constantly having to write 'document.getElementById' and how nice javascript $() frameworks are at accomplishing this.

We'll I just tried out my idea and it seems to work. I don't know if it's the best solution for getting an element By ID but it seems to work in IE6, IE7 and FF (PC & Mac).

function I(i){i=document.getElementById([i]);return i}

I('content').innerHTML = 'Can I get your thoughts?';

Thanks,
Marc

Fotiman

7:04 pm on Nov 28, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



There's no need to assign the element inside your function, you can just return the element. Also, you could create your own $ function if you wanted to (assuming you're not using a framework that already defines this):

function $(id) {
return document.getElementById(id);
}

And then you can use it as in your example:

$('content').innerHTML = 'Can I get your thoughts?';

Fiasst

7:13 pm on Nov 28, 2007 (gmt 0)

10+ Year Member



ah damn, i was so close.. I wasn't sure if that was best practice but was pleasantly surprised when it worked. I usually work with jQuery but when I'm not I'll use this.

Thanks :)

mehh

7:19 pm on Nov 28, 2007 (gmt 0)

10+ Year Member



the $() function I use most can take all sorts of stuff like:
var list=$("id1",["id2","id3"],"id4");
for(;(var el=list.pop());){
document.innerHTML+=el.id+"<br />";
}

will come to
id1
id2
id3
id4

This makes a very handy shortcut in some situations