jQuery append text jQuery append text jquery jquery

jQuery append text


The proper way to append text (constrast with appending HTML) would be:

var someText = "Hello, World!";$('#msg').append(document.createTextNode(someText));

If someText is coming from user input or anything else, it will be properly HTML-escaped. Which should prevent JavaScript injection, the 3rd most common web security vulnerability in the world.

From https://stackoverflow.com/a/944456/122441


Why not use

$('#msg').html('A styled <span style="background: yellow">paragraph</span>');$('#msg').show();

Escape when needed.


I know this question has been answered with different variations but here is one more. I had a similar requirement so spent a little time trying to find a way to do it.

If you know the structure of a HTML, you can get the contents as HTML using jQuery, next change the contents of the same HTML by adding to it.

var lastPageText = $('#test p').html();        $('#test p').html( lastPageText + ' &#128578;' )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><div id="test"><p>This is how things go perfecting well<span> even in a span</span></p></div>