user3101259
user3101259

Reputation: 91

Converting string into jQuery object

I have a string passed to this function, it's an ID of an element. I need it to become a jQ object, is this the correct way of doing it?

passed to function: myfunct('gluk')

myfunct = function(t) {

        var target = $(['#' + t]);
        target.someMethod();

    };

When I use straight $('#gluk').someMethod(); it work fine but not through the function above...

Upvotes: 1

Views: 52

Answers (1)

Jordan Ramstad
Jordan Ramstad

Reputation: 179

Typically doing it that way would remove a lot of the advantages to jquery

Something like this might be a little nicer.

var myfunct = function(t){
    var target = jQuery(t); //use jQuery in case you ever need noConflict()
    //run typical commands
    target.someMethod();
    target.someMethod2();

    //return jquery object for more
    return target;
}

Then you can use myfunct('#id') or var obj = myfunct('#id'), height = obj.height();

If your main worry is having to add the # everytime then you can do it like this:

var myfunct = function(t){
    var target = jQuery('#'+t); //use jQuery in case you ever need noConflict()
    //run typical commands
    target.someMethod();
    target.someMethod2();

    //return jquery object for more
    return target;
}

Upvotes: 1

Related Questions