Dmitriy Bilichenko
Dmitriy Bilichenko

Reputation: 43

jQuery append html with scripts

I need some help with jQuery.

When i'm trying to get html with embded js page content via $.get, it's works good. But when i'm trying to append it to some div, all scripts are removing.

In a console its look fine when i'm doing smthing like this

$('.my_div').html() + '<script>alert("text")</script>'

but when i'm doing

 $('.my_div').html($('.my_div').html() + '<script>alert("text")</script>')

script is running and removing

How can i append html+js code to div without running and removing?

Thanks!

UPD:

My example :

index.html

...

<div class="masonry">
    <div class="a1">
        <p>text</p>
        <script>alert('example')</script>
    </div>
    <div class="a1">
        <p>text</p>
        <script>alert('example')</script>
    </div>
    <div class="a1">
        <p>text</p>
        <script>alert('example')</script>
    </div>
</div>

...

<script>

$.get('get_news.php',function(response){

    $('.masonry').append(response);

});
</script>

...

get_news.php

    <div class="b1">
        <p>text</p>
        <script>alert('example1')</script>
    </div>
    <div class="b1">
        <p>text</p>
        <script>alert('example1')</script>
    </div>
    <div class="b1">
        <p>text</p>
        <script>alert('example1')</script>
    </div>

...

And i'm going to get

<div class="masonry">
    <div class="a1">
        <p>text</p>
        <script>alert('example')</script>
    </div>
    <div class="a1">
        <p>text</p>
        <script>alert('example')</script>
    </div>
    <div class="a1">
        <p>text</p>
        <script>alert('example')</script>
    </div>

    <div class="b1">
        <p>text</p>
        <script>alert('example1')</script>
    </div>
    <div class="b1">
        <p>text</p>
        <script>alert('example1')</script>
    </div>
    <div class="b1">
        <p>text</p>
        <script>alert('example1')</script>
    </div>

</div>

How can i do it?

Upvotes: 1

Views: 3726

Answers (2)

Fabr&#237;cio Matt&#233;
Fabr&#237;cio Matt&#233;

Reputation: 70129

That's the default behavior of .html() - it will strip out scripts and eval them while appending content to the DOM. jQuery even provides $.parseHTML which defaults to stripping out scripts without evaluating them to prevent against XSS.

If you're already executing a script in the page, the vast majority of the time you can just put your code in the same script. But if you really want/need to append a new script to the page, you can do it through append:

$('.my_div').append($('<script>', { text: 'alert("foo");' }));

Fiddle

Upvotes: 1

Infinity
Infinity

Reputation: 3875

You can use append if you don't want to remove the original content. As for stop the script tag from executing, one way is to change to script type to "text/html" or use html escape function.

http://jsfiddle.net/R5xad/

Upvotes: 0

Related Questions