sdfor
sdfor

Reputation: 6458

jQuery - Can I combine object reference with other selectors?

Occasionally I pass an 'object' to jQuery rather than an id or other selectors. For example

<input type="text" onclick="doit(this)" />

<script type="text/javascript">
function doit(e) {
    var a = $(e).val();
}

It is useful when ids are not convenient such as long lists of elements or dynamically created input fields. I actually have seen any examples of passing the object. I just tried it and it works.

My question is: can I combine object selector with other selectors such as I would with ids. so instead of:

$("#myDiv .myClass").something()

I wouldn't know how to code it - something like this maybe:

$(e + " .myclass").something

thanks

Upvotes: 3

Views: 1934

Answers (2)

John Hartsock
John Hartsock

Reputation: 86902

This is one way. using the context parameter in jQuery.

http://api.jquery.com/jQuery/

$(".myclass", e).something();

Upvotes: 2

user113716
user113716

Reputation: 322622

Do this:

$(e).find(".myclass").something();

or the slightly shorter, yet less efficient version:

$(".myclass", e).something();

The reason you can't use + is that your e is a DOM element, which is not a useful type for concatenation into a selector string, since you end up with something like:

"[object HTMLInputElement] .myclass"

Upvotes: 6

Related Questions