iCollect.it Ltd
iCollect.it Ltd

Reputation: 93601

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.

Upvotes: 0

Views: 2203

Answers (2)

kailash19
kailash19

Reputation: 1821

You need to use regex here. Use Javascript .match.

Also, the string you comparing script[type="text/javascript"] is different than the one in the var: <script type="text/javascript">.

You should use it like:

matched = data.match('<script .*</script>');

It will have what was matched.

Upvotes: 3

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93601

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.

Upvotes: 0

Related Questions