1

I wish to append or prepend some html to the page.

Rather than my function going:

var action = 'prepend'; // may be prepend or append
var htmlStr = '<strong>text example</strong>';
var obj = $('#wrapExample');

if(action == 'prepend'){

    $(obj).prepend(htmlStr);

}else{

   $(obj).append(htmlStr);

}

Can I somehow eval the 'action' variable e.g.

eval('$(obj).' + action + '(' + htmlStr + ')');

3 Answers 3

3

Are you perhaps looking for

$(obj)[action](htmlStr)

Saying someobject["something"] and someobject.something are equivalent in javascript.

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

Comments

2

Instead of eval you can use:

$(obj)[action](htmlStr);

The following are equivalent:

a.foo
a["foo"]

Therefore, when you have something like:

var property = "foo";

You can do:

a[property]

to programmatically access a property/method.

Also, since your obj variable is already a jQuery result, you can skip the additional $:

obj[action](htmlStr);

Comments

0

I think it should be eval('$(obj).' + action + '(htmlStr);');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.