8

Why does this execute the <script>:

$('#jq_script').html("<script>$('#test').text('test');<\/script>");

But this doesn't?

document.getElementById('js_script').innerHTML = "<script>$('#test').text('test');<\/script>";

You can see it in action here

From jQuery's documentation about .html():

This method uses the browser's innerHTML property. Some browsers may not return HTML that exactly replicates the HTML source in an original document. For example, Internet Explorer sometimes leaves off the quotes around attribute values if they contain only alphanumeric characters.

2
  • Maybe you have a typo '#jq_script' | getElementById('js_script') Commented Feb 12, 2014 at 17:04
  • because a jQuery developer coded it to make it work. Commented Feb 12, 2014 at 17:11

1 Answer 1

12

html is a jQuery function. innerHTML is a non-standard (but well supported) property.

If you look at the code you will see that .html() parses scripts, and evals them.


To find it in the source:

Find the html declaration: https://github.com/jquery/jquery/blob/1.11.0/src/manipulation.js#L564-604

See it does .append. append in turn calls DomManip[ulate] which will parse and eval scripts.

Relevant bit in DomManip[ulate]: https://github.com/jquery/jquery/blob/1.11.0/src/manipulation.js#L684-709

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

3 Comments

@Linuxios Looks like it's here: github.com/jquery/jquery/blob/1.9-stable/src/… - but I don't immediately see anything about executing scripts. I'd guess it's in some function call
I'm normally very straight-laced on SO as it's not a forum, but I have to say to Frits - your avatar.... Wow! So Doge. Much Lulz.
@Linuxios Another place to look might be: github.com/jquery/jquery/blob/1.9-stable/src/… (for the actual domManip method code that seems to eval the scripts)

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.