简体   繁体   中英

append string with HTML tag in javascript?

I have text like this: "Ngo Kim Huynh ". Then I want to append this text to a div tag in HTML. This is my code:

var text = "Ngo Kim Huynh <the.fallen.angel.9x@gmail.com>";
$("#divContent").append(text);

Only "Ngo Kim Huynh" is shown, because it's understand "the.fallen.angel.9x@gmail.com" is an HTML tag. So, how to show full text?

Escape the brackets (or set it as text):

&lt; is escaped form of < &gt; is escaped form of >

var text = "Ngo Kim Huynh &lt;the.fallen.angel.9x@gmail.com&gt;";
$("#divContent").append(text);

 var text = "Ngo Kim Huynh &lt;the.fallen.angel.9x@gmail.com&gt;"; $("#divContent").append(text); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div id="divContent"></div> 

Use the text() function to append text

 var text = "Ngo Kim Huynh <the.fallen.angel.9x@gmail.com>"; $("#divContent").text(text); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="divContent"></div> 

You can use jQuery text() function. text() will replace the text in element so you need to manually append new text to existing then update the element content using text()

Please see the fiddle https://jsfiddle.net/ponmudi/2r5jg802/

HTML

<div id="divContent">My default content</div>

Script

var text = " Ngo Kim Huynh <the.fallen.angel.9x@gmail.com>"; $("#divContent").text($("#divContent").text()+text);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM