1

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...

1
  • 4
    You don't need the brackets, just $('#' + t). Commented Dec 14, 2013 at 1:15

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

no need to suggest using "jQuery" , very easy to make $ alias useable in a noConflict situation
Just a little thing I do, I never use $ just in case I ever run into that situation. Good habit to have especially when using Joomla on a regular basis. This way if you coded it "fast" then had to use no conflict you would not have to go back through your code. Plus i hate the look of the code with $, looks untidy, but that's personal preference.
jQuery(function($){ /* $ is insulated */})... a lot of extra work typeing jQUery when it's not needed
Its just all preference, not going to deny the fact that some people might prefer that, also this is the way I would prefer in that case (function($){ /*code */})(jQuery). 90% of the JS work I do has to deal with noConfict, so I just got in the habit of using jQuery rather then $ so I never accidentally have a conflict issue. To make this a little bit more of a learning comment, if you use a CMS it will typically use noConflict to make sure something like mootools can be used with jQuery, so using an anonymous function or similar would create issues when using both in your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.