views:

30

answers:

3

I have a script block, in the div element which is appended after html response. I want to access this block and call eval() function for this script. How can I access the script block.

I tried $("#divId script") , but it doesn't work.

<div id="divId">
    <script type="text/javascript">
    ....
    ....
    </script>
</div>
+1  A: 

Not sure why it doesn't work in jQuery, but plain DOM should work...

$(document.getElementById('divId').getElementsByTagName('script')[0])
Jhong
Plain dom works but I need jquery.
penguru
Why? See my edit.
Jhong
penguru, please read up on what jQuery is... it's not a **replacement** for plain DOM methods, it's an **extension**. You can mix the two together perfectly (if you keep track of what you're doing). If Jhong's method works, simply wrap that in a `$()` and you're done. If that isn't the problem... well, it isn't.
MvanGeest
P.S. @penguru I agree with the others that you don't need to do this... I'm simply providing the solution you asked for.
Jhong
+2  A: 
$("#divId script").html()

If you don't trust me, click http://jsfiddle.net/VZfMd/

umpirsky
+3  A: 

$("#divId script") works fine for selecting the element, but here's the problem: $("#divId script").text() doesn't work in IE because jQuery isn't set up to handle the cross browser discrepancies of text nodes in script elements.

IE requires that you access the .text property of the script element, other browsers require that you access .textContent. The following works for me:

var scr = $("#divId script")[0],
    txt = "textContent" in scr ? scr.textContent : scr.text;

eval(txt);    

Example

Andy E