views:

2731

answers:

5

Since the getElementsByTagName() function is new (DOM-1?) I wanted another more reliable method to get a reference to an element based on its tag name/id.

Edit- Without using a framework, since I need to cut down on size; so 10-20K for a framework is unacceptable. I just need the JS code that can fetch an element

+3  A: 

As mentioned, getElementsByTagName is not new...

I think you're going to get about 10 references to jQuery.

Returns all the paragraph elements:

$('p').length

If 19kb is too big, and you just want to do element selection, something like sizzle works well, at about 4kb. The only thing I would note is that you're probably going to end up needing something that's in jQuery anyway.

http://sizzlejs.com/

Queries are very similar:

Sizzle("li");

19kb is a really small one-time price to pay for the power of jQuery.

altCognito
What about those window[id?] and document[id?] .. would those do?
Jenko
I've yet to find a reason *not* to use jquery. It's just so elegant and easy to use...
Zack
Not sure why you would want to do that, my answer would be no.
altCognito
I need to cut down on size so 10-20K for a framework is unacceptable. I just need the JS code that can fetch an element.
Jenko
A: 

Or prototype, etc. You'll need to use one of these javascript glue libraries to achieve this. All of them will call this function if it exists, but fake it otherwise.

Adam Luter
Yep. :) Exactly.
altCognito
+3  A: 

If all you want to do is select elements, it may be smart to just use the sizzle selector engine and not a full blown library. I would go with the full library, but, going with a selector engine might be useful in limited circumstances.

Sizzle is the CSS selector engine that powers jQuery.

http://sizzlejs.com/

KyleFarris
+10  A: 

getElementsByTagName is not new. It is supported since IE5, FF1 and Opera 7 according to w3schools

[edit] Thanks for pointing this out. It was indeed supported since Opera 7.

Nadia Alramli
Thanks for the clarification. That was a really old rumor.
Jenko
Its Opera 7, and all versions of Mozilla and Safari -- according to "undefined".
Jenko
Actually Opera had it as far back v7. See http://www.opera.com/docs/specs/opera7/js/dom/
JPot
Don't forget the any bugs: http://ejohn.org/blog/object-getelementsbytagname-ie7-bug/
altCognito
A: 

Last time I tried testing the performance of ‘==’ vs. ‘===’ I didn’t notice any difference. In theory it should be faster because the interpreter has less to think about, but that would depend on how the interpreter has been coded I guess.

Cek