jQuery append text
Solution 1
$('#msg').append('Some text').show();
Solution 2
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
Solution 3
Why not use
$('#msg').html('A styled <span style="background: yellow">paragraph</span>');
$('#msg').show();
Escape when needed.
sunjie
Updated on November 14, 2020Comments
-
sunjie over 3 years
I want to append some simple data in a div like:
$('#msg').append('Some text');
In the body, i think i will need to place the the html like.
<div id="test"> <div id="msg"></div> //show text inside it. </div>
However, I want to add some CSS to the
#msg
. For example, background color. Now the problem is that, since the#msg
div is present all the time, i see the background color even when the text is not appended to it. I have tried to add css like "display:none, but in that case i can not see the text appended to it. Can i do it so that the#msg
div appears inside the#test
only when the text is appended to it? Thanks. -
sunjie almost 13 yearsThanks. This works but just wondering how? The #msg div remains in the html, but how it doesnt apply the css unless the jquery uses show?
-
Naftali almost 13 years@sunjie --
show()
just removes thedisplay: none
and turns it todisplay: block
-
usr over 11 yearsThis does not append text, it appends HTML. Big difference.
-
Hendy Irawan about 11 yearsAgree with @usr. If the "text" is coming from user input, this will cause JavaScript injection.
-
rbhitchcock almost 10 yearsThis should be the accepted answer. Thanks for posting this along with the explanation of why it's the correct way to safely append text to an element.
-
Gui Imamura almost 9 yearsWould
$('#msg').text( $('#msg').text() + 'Some text' )
be safer? According to the jQuery API,.text( [text] )
escapes the text with.createTextNode()
. -
AsgarAli over 8 yearsDon't know why people are ranking negative to your answer. You have answered correctly.
-
DevAntoine about 8 years@AliKhanusiya Because .append() appends HTML and not text.
-
DevAntoine about 8 years@AliKhanusiya You maybe need to read it too: "content: DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements."
-
Reporter about 6 yearsThe method .html() does replace the existing content by new one. I think the questioner was not aware there is a tiny and important difference between replacing and appending.
-
E.Serra about 5 yearsthat's the exact definition of append IMHO
-
Syfer about 5 yearsI never said this is the best way it's another way if someone wants to try. Sometimes you have a platform element you can't change.