var str = '<script>alert(1)</script>';
var decoded = $("<div/>").html(str).text();
//document.write(decoded); THIS WORKS, but I want to avoid using document.write
var para = document.createElement("script");
var node = document.createTextNode(decoded);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
The problem is that due to presence of script tag, this createElement method won't work. Closing script tag in the encoded str will cause syntax error (Uncaught SyntaxError: Unexpected token '<'). Document.write works all perfect but I want to avoid due to its disadvantages of parser-block etc.
In real use case, the encoded string will be of some ads which will be entered by users. Please note we can't remove script tags from code they enter and are saving it in database by using htmlentities($adcode).
User input is trusted, so no issue of any xss vulnerability which might happen by solution proposed.
One of the sample user input :
<script async="async" src="someURL.js"></script>
<script>
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
</script>
<div id="xyzid">
<script type="text/javascript">
googletag.cmd.push(function() {
googletag.pubads().display("Mobile_ATF_300x250", [300,250],"div-gpt-ad-0");
});
</script>
</div>
There can be various different version of ad set with unknown pattern.
Additional not so relevant info : We will be further using something like <script> if(var==1) { codeblock1 } else { codeblock2} </script> (here codeblock is 1st code blockset). So any soln which includes use decoded user input directly won't be useful as the script block will break in if-else.