Search code examples
jqueryjquery-selectorsscript-tag

JQuery selector to match a dynamically loaded script tag


I want to match any raw script in an Ajax downloaded document, so I tried

$.ajax({
    url: url,
    type: "post",
    success: function (data, status, xhr) {
        var scr = $(data).find('script[type="text/javascript"]');

The call is returning sucess, but the selector is not returning a match i.e. 'script[type="text/javascript"]' has a length of 0.

The page being loaded (i.e. data) definitely contains a test script tag like this:

    <script type="text/javascript">
        $(function () {
            alert("JS running");
        });
    </script>

What am I missing here? Is it the way JQuery parses raw HTML?

Followup:

this also returns no matches: var scr = data.find('script');

Note: Looking at the contents of $(data) it appears the JQuery parser strips out any Javascript tags.


Solution

  • It appears that $(htmlstring) strips any script tags from the HTML. That is a shame.

    The solution I came up with is based on the regex in the answer to How to get regex to match multiple script tags?

            var re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
            var scripts = "";
            var match;
            while (match = re.exec(data)) {
                if (match[1] != "") {
                    scripts += match[0];
                }
            }
            panel.append(scripts);
    

    I concatenate any inline scripts and the script executes immediately upon being appended to the DOM.