最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Aug 13, 2013 at 17:59 Kai HusenKai Husen 1031 silver badge7 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 5

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/w3UF4/

You can do this with plain 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/hunter/YG48U/

发布评论

评论列表(0)

  1. 暂无评论