views:

46

answers:

3

If I have the following HTML:

<div id="container">
  <iframe></iframe>
</div>

What is the most effective way (mainly in terms of performance) to create a reference to the <iframe> DOM element? I'm using something like the following:

var element = document.getElementById('container').getElementsByTagName('iframe')[0];

IIRC, though, getElementsByTagName can be a slow performer. Is that not an issue since there's only one element within the <div id="container"> anyway?

Is there a more concise, and/or better-performing way to get the <iframe> here? It's safe to say that it will always be the only child of <div id="container">, but not always the only <iframe> on the page.

+4  A: 

Put an ID on the iframe and reference it with gEBI. If you're not noticing any latency with gEBTN then I suggest keeping the code the same as is, and yes providing a context for gEBTN helps.

meder
Thanks, meder! For this project, I'd rather not add an ID to the <iframe>, as this is a widget intended for use on any Web page and I'd like to avoid even the minute chance of a conflict. The ID "container" will be actually be something specified by the owner of the page hosting the widget. Good to know that using gEBTN in context improves performance.
Bungle
+3  A: 

In this case you wont notice the performance. If you would however do document.getElementsByTagName you would probably notice it as it has to walk the entire DOM tree.

Remember that it´s not always about performance, in many cases it´s better to have clear readable code then a perl-one-liner that will look like jibberish to anyone, including you, when they revisit it after 2 weeks.

If you can add an id attribute to the iframe element that would of course be the best solution as Meder says.

anddoutoi
Thanks, anddoutoi - good points to keep in mind!
Bungle
A: 

Hmm it seems it is all right with code. I think you can forget about performance for such simple javascript code.

Danil