Call the jQuery library function with variable

advertisements

I build recurring html with jQuery functions.

I'd like to give my functions more flexibility with $.append(), $.before(), and $.after(), etc.

Currently, I do something like

$.fn.appendRecurringHTML = function(domInsertMethod, domInsertID, htmlToInsert) {
    if(domInsertMethod == 'append'){
        $(domInsertID).append(htmlToInsert);
    }
    else if(domInsertMethod == 'before'){
        $(domInsertID).before( ...
}

but I'd prefer (pseudo)

$.fn.appendRecurringHTML = function(domInsertMethod, domInsertID, htmlToInsert) {
    $(domInsertID).window[domInsertMethod](htmlToInsert);
}

but that doesn't work for me.

Is this possible? If so, how?


Just use

$(domInsertID)[domInsertMethod](htmlToInsert);

DEMO: http://jsfiddle.net/UZKLY/

This works because the result of $(domInsertID) (or any $()) is a jQuery object, so it has properties and methods you want to call. Normally, you use dot notation to access them, but bracket notation is just as valid to use. Bracket notation is the only way to dynamically get a property/method (and allows for invalid identifier characters).

But be careful, because technically any method name could be provided, and therefore called. So it's up to you if you want to allow it or not.

As it stands, it doesn't make sense to add to $.fn, because you're not actually using the selected elements from the selector. It makes more sense to me to use this setup:

$.appendRecurringHTML = function(domInsertMethod, domInsertID, htmlToInsert) {
    $(domInsertID)[domInsertMethod](htmlToInsert);
};

And you would call it like:

$.appendRecurringHTML("after", "#id", "html");

But if you wanted to use the selected element(s) as the target(s), you could use:

$.fn.appendRecurringHTML = function(domInsertMethod, htmlToInsert) {
    return this.each(function () {
        $(this)[domInsertMethod](htmlToInsert);
    });
};

And call it like:

$("selector").appendRecurringHTML("after", "html");

DEMO: http://jsfiddle.net/UZKLY/1/

It preserves chaining, and will be applied to all matched elements.