1

My code uses a jQuery plugin that inserts some HTML code.

I have the option to change the inserting method, by setting them via variable.

The variable is called:

var options = {insert: 'append'};

I don't want to do that with an if condition, like that:

if(options.insert === 'append') {
 $('#foobar').append(htmlcode);
}else if (options.insert === 'prepend'){
 $('#foobar').prepend(htmlcode);

... and so on.

Is there any solution to insert the html code with a given varibale method?

0

1 Answer 1

6

Because the jQuery construct is an object, you can use bracket notation to access functions. Try this:

$('#foobar')[options.insert](htmlcode);

So long as options.insert matches the name of a function, it'll work.

Example fiddle

Sign up to request clarification or add additional context in comments.

2 Comments

Nice one. I didn't know about that.
Good answer. Newer thought about this :)

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.