Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> 

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.

like image 738
sunjie Avatar asked Jul 05 '11 20:07

sunjie


People also ask

How do you append something in jQuery?

jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.

How do I get inner Text in jQuery?

Answer: Use the jQuery text() method You can simply use the jQuery text() method to get all the text content inside an element. The text() method also return the text content of child elements.

How append a div in another div using jQuery?

First, select the div element which need to be copy into another div element. Select the target element where div element is copied. Use the append() method to copy the element as its child.


2 Answers

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

like image 115
Hendy Irawan Avatar answered Oct 14 '22 21:10

Hendy Irawan


Why not use

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

Escape when needed.

like image 39
WesternGun Avatar answered Oct 14 '22 21:10

WesternGun