选择具有给定id的元素的更快方法 [英] Faster way to select an element with a given id

查看:54
本文介绍了选择具有给定id的元素的更快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题.假设我们有以下html标签:

 < div id ='foo'>我是div</div> 

他的div位于dom上(不是由javascript生成的)

如果我想在javascript中多次使用此div,这是更好的方法吗?

  • 将其存储在这样的变量中:

    var d = $(#foo")

  • 还是每次使用jquery调用它?: $(#foo").methodName()

哪种方法所涉及的dom遍历较少?

解决方案

最快的方法是:

  document.getElementById("foo"); 

将此变量设置为可重复使用的变量将避免需要一遍又一遍地找到它,所以是的.

如果要使用它制作jQuery对象:

  var fooDiv = document.getElementById("demo");var $ fooDiv = $(fooDiv); 

I have a question. Let's say we have the following html tag:

<div id='foo'>I am a div</div>

Τhis div exists on the dom(it is not generated by javascript)

If I want to use this div in javascript many times which is the better way to do it?

  • store it in a variable like this:

    var d = $("#foo")

  • or call it every time with jquery?: $("#foo").methodName()

Which method does involve less dom traversal?

解决方案

The fastest way is:

document.getElementById("foo");

Setting this to a variable for reuse will prevent the need to find it over and over again, so yes that is the way to go.

if you want to make a jQuery object out of it:

var fooDiv = document.getElementById("demo");
var $fooDiv = $(fooDiv);

这篇关于选择具有给定id的元素的更快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆