Dev Tip: Faster Selects w/Tag Name

Posted on by

jQuery provides an extremely versatile DOM query mechanism. If you’re wondering what’s happening under the covers, and if there are less- and more-performant ways to formulate your query . . . the answer is YES. In many cases you can help jQuery by specifying a tag name, i.e.:

$("div.class").show()

is faster than:

$(".class").show()

. . . with the difference being that the query engine can narrow by tag name first. It’s smart like that.

So, you shoud be in the habit of specifying a tag name. The only exception: getting by ID. If you’re getting by ID, do not include a tag name, or anything else besides the ID selector.

Note that the second example here (with the class selector only) is perfectly valid, and if you need to query for multiple element types, by all means go ahead — jQuery will still return the correct results.

5 thoughts on “Dev Tip: Faster Selects w/Tag Name

  1. Joe Kohlmann on said:

    Would JQuery also perform faster if the element selector hierarchy were more directly specified in the $() function query?
    Example:
    $(‘#content dl dt a’) versus $(‘#content dt a’)
    Thanks for the tip, by the way.

  2. Andre Lewis on said:

    Joe K: In that case, the less that is specified, the faster it is.
    $(“#foo a”)

    will always be faster than
    $(“#foo div a”)

  3. refactored on said:

    Didn’t Klaus Hartl get better performance from jQuery using “el>el” in his Tab plugin?

  4. Chris Domigan on said:

    On a related note, does anyone know if browsers implement CSS faster if your style sheets are similarly structured? i.e. with element.class instead of just .class.

    Obviously when it comes to structuring your style sheet/s it’s a lot easier having just the class name so you can tell at a glance what the style is for!

    Chris