Manos Kounelakis Manos Kounelakis - 9 months ago 31
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?:
    $("#foo").methodName()



Which method does involve less dom traversal?

Answer Source

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);