Solution 1 :

You can try using selector and text function:


This should insert only the text, not the html.

Note: as mentioned in comments, this approach will erase the entire content of that div.

In order to keep the existing content you can append to existing value like this:

//Get the existing text
var existingText = $("div#messages").text();

// Insert the already existing text plus the new one
$("div#messages").text(existingText + '<script>alert()</script>');

Or you can do it in one line:

$("div#messages").text($("div#messages").text() + '<script>alert()</script>');

Or you can use the callback mentioned in the comments by @Chris.

Problem :

I have a piece of code that uses Jquery’s .append method. If you put any markup inside the string it needs to append it treats the markup as valid and instead of putting it as a string it appends it as html. how could I stop this?


var msg = "<script>alert()</script>"

this would make an alert box pop up when I want it to just put <script>alert()</script> in the div.

is there a different method I should use?


Comment posted by Chris Brenberg

Be aware that this would clear any existing text and replace it with new text. To append text to existing text, you’d have to use the