Search code examples
javascriptjqueryhtmldomdom-traversal

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>

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


Solution

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