3

I wrote something that uses document.getElementById a lot so I was wondering if instead I should just make a function like:

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

and then just call it like:

alert(gid("test").innerText); 
1
  • Oh I see. Sorry, I didn't know you had to do that. Commented Jul 11, 2011 at 21:01

5 Answers 5

8

No, there's no reason not to. Typically most people use jQuery for stuff like this though.

Sign up to request clarification or add additional context in comments.

5 Comments

Right, but I was having trouble with it because jquery's .text() wasn't keeping the formatting like .innerText was.
you can always take a jquery result and add .get() which will basically get your DOM element, then you can use any valid DOM method.
Just to add something about different (and maybe even better) framework: in MooTools the shorthand is document.id().
How does .get() work? You mean I can do something like $("#test").get(innerText);
$("#test").get(0).innerText-- $() doesn't return a DOM object but a jQuery object containing an array of objects matching the criteria of the selector; and the get() method as defined on jQuery objects returns the DOM object at the given index (whatever argument you send to get()). 0 is the first item in the array. $() always returns an array, even if only one item matches the selector. which is why you'd usually use .get(0).
2

It's a good idea - it'll aid minification (if you chose to minify) and will save annoying spelling mistakes when you accidently type document.getElementsById. You can also shorten document.getElementsByTagName if you use it a lot.

1 Comment

I agree James! I think it makes sense.
1

I don't think it's a bad idea. For one calls to gid() are going to be shorter than document.getElementById(). Plus you now have the ability to modify what is in your gid function so that you can use something other than document.getElementById.

Comments

1

Using document.getElementById will only make it faster when you have a huge javascript and not using any standard library like JQuery.

Comments

0

I'm not saying that you should not provide a replacement function, but there are some downsides so you should make sure the balance is in favor of changing. A couple reasons not to shorten it:

  1. It's now non-standard looking code that other people who know DOM/Javascript won't recognize and will have to learn before they can make sense of.
  2. It's one extra function call so presumably, your new extra function isn't quite as fast.
  3. You are losing the functionality of addressing different documents or document fragments (though not used very frequently).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.