EDIT: filter() was oviously wrong. Changed it to find(), however the problem remains.
This code works for me:
$('#content')
.replaceWith($(
'<div>
<div id="content"> Hello <script type="text/javascript"> alert(123); </script>
</div>
</div>
'));
But this does not:
$('#content')
.replaceWith($(
'<div>
<div id="content"> Hello <script type="text/javascript"> alert(123); </script>
</div>
</div>
').find('#content'));
The only difference is that in the second example I want to filter only one part of the HTML and then insert that into the DOM.
Any ideas? Thanks.
EDIT3: Added the solution as answer
This works for me:
var newElements = $('<div><div id="content"><script>alert(123)</script></div></div>');
if (newElements.length > 1) {
for (var i = 1; i < newElements.length; i++) {
$('body').append(newElements[i]);
}
}
$('#content').html(newElements.find('#content').html());
The reason is that creating the elements in the first call, sorts out all script tags and puts them in an array.
console.log($('<div><div id="content"><script>alert(123)</script></div></div>'));
Result:
[div, script]
Then obviously when applying .find() to that array the script tags are lost.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.