简体   繁体   中英

How do I convert an HTML string to plaintext and append it to a DIV in JavaScript?

Here is my issue:

I have a text variable that I get back from a jQuery post request. I parse the JSON and run a for loop. Inside the object I have some variables that look like the below.

post_content: "<iframe src="THEURLREMOVEDFORQUESTION" height="281" width="500" allowfullscreen="" frameborder="0"></iframe> Ready to plan you first visit? <a href="THEURLREMOVEDFORQUESTION">Click here</a>."

So when I append this to a DIV the whole iFrame appears. Does anyone know if there is a function I can use to print the characters and not render the HTML? Basically is there an easy function I can use like encode(); or something?

Sorry if this is a duplicate. I searched for awhile and didn't find anything.

You should set the .text() of the div, so it won't render the HTML, sample:

<div id="test"></div>

$("#test").text("<p>See this is showing the tags</p>");

Demo: http://jsfiddle.net/w3UF4/

您可以使用纯JavaScript执行此操作:

myDiv.appendChild(document.createTextNode(post_content));

If you want to append new content to a div that may already have content use text() and append()

<div id="container"></div>

$("#container").append($("<div>", { text: data.post_content }).html());

example here: http://jsfiddle.net/hunter/YG48U/

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