jQuery append text
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&开发者_如何学运维gt;
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.
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 + ' 🙂' )
<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>
Hope the above helps someone looking for similar answer
Cheers
You can do this using multiple ways. You can create a css class and do this:
Method 1
CSS:
.hello{ background-color: green }
HTML
<div id="msg"></div>
Javascript:
$("#msg").append("hello world").addClass("hello");
Method 2
HTML
<div id="msg" class="hello" style="display:none;"></div>
CSS:
.hello{ background-color: green }
Javascript:
$("#msg").append("hello world").show();
Method 3
HTML:
<div id="msg"></div>
Javascript:
$("#msg").append("hello world").css("background-color","green");
$('#msg').append('Some text').show();
精彩评论