0

Which is better to use and why?

if ($(target).parents('div#test').length) {

or

var target = $(evt.target); 
if (target.parents('div#test').length){
jondavidjohn
  • 61,812
  • 21
  • 118
  • 158
Hussein
  • 42,480
  • 25
  • 113
  • 143
  • 1
    I'm sure this is just an example, but when selecting by ID it's faster and easier to just use `$('#test')`. You don't have to use `.parents()` since the ID is unique within the document. – user229044 Feb 07 '11 at 20:38

1 Answers1

2

There are preformance gains to be had in using the second option. If you are going to reuse the selector multiple times.

Essentially you are caching your DOM traversal if you use the same selector multiple times.

See this answer for more details

Community
  • 1
  • 1
jondavidjohn
  • 61,812
  • 21
  • 118
  • 158