1

I have a DIV I want to ajax-load. The contains javascript that needs to run. I ran across this SO article that talks about loading the scripts after the main content has loaded. However I cannot get it to work, primarily because I can't find the scripts in my content!

Consider the following:

$('<p />').html('<div>x</div>').find('div').html()
"x"

(for some reason the line below wouldn't work:

$('<p><div>x</div></p>').find('div').html()
null

However, there's something special about scripts:

$('<p />').html('<script>x=1</script>').find('script').html()
null

what am I doing wrong here?

Community
  • 1
  • 1
ekkis
  • 9,804
  • 13
  • 55
  • 105
  • 1
    FYI, The reason this doesn't work: `$('

    x
    ').find('div').html()` ...is that it isn't valid for a `

    ` element to have a `

    ` element as a descendant. The browser is kicking it out.
    – user113716 Jun 28 '11 at 20:33
  • hmm... `$('

    x

    ').find('p').html()` does work - however `$('
    ').find('script').html()` doesn't...
    – ekkis Jun 29 '11 at 00:28
  • Yes, `$('

    x

    ').find('p').html()` works because it *is valid* to have a `p` as a child of `div`. The reverse is not valid, which is why `$('

    x
    ')...` doesn't work. The reason `$('
    ')` doesn't work is because... well see the answers below. ;o)
    – user113716 Jun 29 '11 at 00:33
  • @patrick dw, the answers below don't really address the issue – ekkis Jul 02 '11 at 00:33

2 Answers2

0

Script tags get scrapped from jQuery .html()

Naftali
  • 144,921
  • 39
  • 244
  • 303
0

Neal is right. I'd recommend adding the script tag with plain JS:

var scriptTag = document.createElement('script');
script.text = 'alert("testing");';
// if you're linking to a remote script, use script.src instead

document.getElementById('parentID').appendChild(script);
// to append to the body, use document.body.appendChild
Pendlepants
  • 199
  • 2
  • I can't because I'm not building this myself. I'll get a string from somewhere and it may have a script section in it – ekkis Jul 02 '11 at 00:32