views:

620

answers:

5

I'd like to pass the ID of an element into a function which then calls jQuery. However, I'm stumped as to how to actually take the ID variable and concatenate it with other text inside the jQuery statement. For example, this returns an error:

myFunction("#myObject");

function myFunction(IDofObject){

    $("'"+IDofObject+" img'").doSomething...

}

I'd like to do something with '#myObject img' but can't get that to work inside the statement.

+1  A: 
myFunction("#myObject");

function myFunction(IDofObject){

    $(IDofObject+" img").doSomething...

}

Try that.

inkedmn
+4  A: 

Don't wrap the parameter in quotes:

function myFunction(IDofObject) {
    $( IDofObject + " img" ).doSomething();
}

Also, you may want to consider adding the hash character inside the function so you can pass it the actual id, not a selector.

myFunction( $('.classSelector :first').attr('id') );

function myFunction(IDofObject) {
    $( "#" + IDofObject + " img" ).doSomething();
}
tvanfosson
You beat me to it! ;)
DA
A: 

Ugh. one of those '2 seconds after you ask you figure out...' questions:

function myFunction(IDofObject){

    $(IDofObject+" img").doSomething...

}
DA
A: 

Just do this--

myfunction('obj')
function myfunction(obj){
$('#'+obj+' img').show();
}

Or, even

myfunction($('#2 img a'));

myfunction(jqobj){
jqobj.show();
}
CodeJoust
+1  A: 

I think you'd get better reuse if you passed an entire selector as a parameter, remembering that jQuery implicitly iterates over all matched elements. For a rudimentary example:

function hideImageDescendants(selector){
    $(selector).find("img").hide();
}
karim79