You can try using selector and text
function:
$("div#messages").text('<script>alert()</script>');
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.