<!DOCTYPE html>
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<div id="hel"></div>
<script>
txt="<script>alert('Test');</script>";
var headerIcon = '<div>hi</div>';
var messageBox = $("<div class='textDiv'><span class='sp'></span></div>");
$(document).ready(function(){
messageBox.text(txt);
//$(".textDiv .sp").text(txt);
$('#hel').append(headerIcon,messageBox);
});
</script>
</body>
</html>
The output is
hi
<script>alert("Test");</script>
But if I use $(“.textDiv .sp”).text(txt); instead of messageBox.text(txt); the output is only
hi
What is going wrong when i use $(“.textDiv .sp”).text(txt);?
Edit : I dont want to inject html.I want to display as text only. But i just want to know why messageBox.text(txt); works but $(“.textDiv .sp”).text(txt); doesnt
Try something like this. As far as I understand you, it should help:
$(".textDiv .sp")is in message box when you call$(".textDiv .sp").text(txt), but not in a DOM. That is why it finds nothing ($(".textDiv .sp")will search only elements already in DOM). Another approach:$(".textDiv .sp", messageBox).text('txt');– second param here strictly say that jQuery should search insidemessageBox. It is eqvivalentto messageBox.find(".textDiv .sp").text("txt");And just like it was mentioned by other users – in case you want to get
"<script>alert("Test");</script>"executed – you should use.htmlinstead of.text