Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top