jerome
jerome

Reputation: 4977

jQuery selector question

I have encountered code that leverages jQuery, similar to the following.

NAMESPACE = {
    propertyA : $("#selector-a"),
    propertyB : $("#selector-b")
}

$(NAMESPACE.propertyA).click(function(){
    // ...
});

This seems to work, even though the syntax for attaching the click handler should be.

NAMESPACE.propertyA.click(function(){
    // ...
});

Does jQuery have the built in ability to resolve the following, despite the incorrect syntax?

$($("#my-selector")).click ... etc.

Upvotes: 1

Views: 67

Answers (2)

Dan Herbert
Dan Herbert

Reputation: 103377

Yes. jQuery allows as arguments to the $:

  • A CSS selector
  • A DOM element
  • An array of DOM elements
  • A jQuery object
  • A function (which will be called as part of $.ready())

All of these are valid syntax as far as jQuery is concerned, though performance may suffer in some of these cases.

Since your NAMESPACE.properties are jQuery elements, this will work.

Upvotes: 3

Sampson
Sampson

Reputation: 268324

Yes, it will handle this if necessary. You really ought not use this syntax though if it's within your control. I tested against the following and got the same results with both:

$($("li")).click(function(e){
  alert(e.target);
});

//--

$("li").click(function(e){
  alert(e.target);
});

Upvotes: 1

Related Questions