开发者

What is the most effective way to create a reference to this HTML element using plain JavaScript?

开发者 https://www.devze.com 2022-12-11 06:41 出处:网络
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 &l

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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消