views:

50

answers:

2

Say I have a something like this:

<p id="script">$("p").css("color", "red");</p>

Is there a way to select the script contained within the tag and execute it using jQuery? In this case, the script

$("p").css("color", "red");

would be executed and then cause itself to be rendered with a red font color within the paragraph tag. I can select the text perfectly fine, but haven't found a way to actually execute it. I don't want other solutions - I am aware of them, I am just trying to figure out if this specific case is possible, and if so, how. Thanks.

+1  A: 

You can call eval() on it, though I would re-evaluate your approach, like this:

eval($("#script").html());

You can test it out here. This is just illustrating it can be done, but you should try and avoid this if at all possible, it has security and performance issues at the very least.

Nick Craver
Wouldn't this break if the code happened to have any markup? For example if code highlighting has been applied to that block of code.
CD Sanchez
@Daniel - If there's something other than code in there nothing would be safe really...not that it's safe to start with.
Nick Craver
Beauty! I just want to clarify that this is not for a webapp, just something I am playing around with and this is exactly what I wanted because I am 100% controlling the content that will be run inside the eval(). I would NEVER use this in the wild. Thanks! :-)
Kamikaze Mercenary
@Kamikaze you have got the name for it though....
Jon
+4  A: 
eval($("#script").text())

Since it uses text(), it should strip out any HTML so you should be able to apply any code highlighters to the code if you wanted to.

For example, if you were using the StackOverflow code highlighter and wanted to select the code, text() would return what you expect:

eval($("#script").text())

Whereas html() would probably return

<span class="kwd">eval</span><span class="pun">(</span><span class="pln">$</span><span class="pun">(</span><span class="str">"p #script"</span><span class="pun">).</span><span class="pln">text</span><span class="pun">())</span><span class="pln"><br></span>

Which obviously can't be evaluated.

If you don't plan on doing any code highlighting then it's a non-issue.

CD Sanchez
Keep in mind this isn't the same result, for example: http://jsfiddle.net/nick_craver/rBhJq/ vs http://jsfiddle.net/nick_craver/rBhJq/1/ depends which behavior you're after...but in this case the OP has complete control over the markup and isn't using highlighting so it's a moot point anyway I suppose.
Nick Craver
@Daniel you should correct your selector for future users finding this question.
Nick Craver
@Nick Craver: Thank you for pointing it out. Fixed.
CD Sanchez