jquery html() strips out script tags

This is the easiest solution:

var keepScripts;
keepScripts = true;
$.parseHTML(yourHtmlString, keepScripts);

This will keep the script tags in ;)


Edit: I'm tired and not thinking. You can just use the native innerHTML method instead of .html():

$('#feedback-' + idfeedback)[0].innerHTML = x;

Original answer:

My hunch is that the answer you linked doesn't work for you because the included scripts are called with a src attribute rather than script content between the <script> and </script> tags. This might work:

$.ajax({
    url: 'example.html',
    type: 'GET',
    success: function(data) {

        var dom = $(data);

        dom.filter('script').each(function(){
            if(this.src) {
                var script = document.createElement('script'), i, attrName, attrValue, attrs = this.attributes;
                for(i = 0; i < attrs.length; i++) {
                    attrName = attrs[i].name;
                    attrValue = attrs[i].value;
                    script[attrName] = attrValue;
                }
                document.body.appendChild(script);
            } else {
                $.globalEval(this.text || this.textContent || this.innerHTML || '');
            }
        });

        $('#mydiv').html(dom.find('#something').html());

    }
});

Note, this has not been tested for anything and may eat babies.


I had the same problem, but with more issues which I couldn't fix that easily. But I found a solution:

This is my pseudo-source (HTML) that I couldn't change in any way.

<html>
  <body>
    <div id="identifier1">
      <script>foo(123)</script>
    </div>
    <div id="identifier2">
      <script>bar(456)</script>
    </div>
  </body>
</html>

I used $.get() to fetch this HTML page. Now that I have the code as a string, it's time to search in it with jQuery. My aim was, to isolate the Javascript-Code inside the <script>-Tag, that belongs to the DIV identifier2, but not to identifier1. So what I wanted to get is bar(456) as a result string. Due to the reason, that jQuery strips all script-Tags, you cannot search like this anymore:

var dom = $(data); //data is the $.get() - Response as a string
var js = dom.filter('div#identifier2 script').html();

The solution is a simple workaround. In the beginning we will replace all <script>-Tags with something like <sometag>:

var code = data.replace(/(<script)(.*?)(<\/script>)/gi, '<sometag$2</sometag>');
var dom = $(code);
var result = dom.find('div#identifier2 sometag').html(); 

//result = bar(456)

It's a simple hack, but it works!