Manos Kounelakis Manos Kounelakis - 1 year ago 59
jQuery Question

Faster way to select an element with a given id

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

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

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?:

Which method does involve less dom traversal?

Answer Source

The fastest way is:


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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download