jQuery - Is it okay to use $('#ElementId') everytime?

倖福魔咒の 提交于 2019-12-01 20:20:26

DOM selection is expensive. Cache it.

var x = $('#MyElement');

Here's a jsPerf test. In Chrome 13 on Mac OS X, the variable reference is over 1,000 times faster.

This is not only due to the DOM selection of course, but also the construction of the jQuery object.

Considering that the second code only queries the DOM once for x, yes, it is a much better idea to store the jQuery object.

why not?

var x = $('#MyElement').text();
$('#MyParentElement').html('<tr id="' + x + '"><td>' + x + '</td></tr>';

Someone correct me if I'm wrong, but it's my understanding that if you used the second option (ie var x = $('#myElement')) that it wouldn't update dynamically. If #myElement changed, as elements sometimes do, you'd still be referencing whatever it was when you assigned its value to X.

If you don't feel like #myElement is going to change, then go ahead and use the var x option. As others have said, it's a bit quicker.

Storing $('#MyParentElement') in a variable would be faster, however by a small margin since selection by element ID is fast. Though if building a large JS app then it could add up.

It's about as okay as calling document.getElementById every time would be.

Technically it is better to go with your second option, and store the result to a variable if you will be accessing it repeatedly. But in practical terms, unless you have hundreds of references to the same element then the difference is not going to be noticeable to the user.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!