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

javascript - Append HTML-escaped text: jQuery - Stack Overflow

programmeradmin2浏览0评论

I'm used to using jQuery's .append() method to add text or HTML onto the end of a pre-existing element. I'm currently using jQuery's .text() to escape strings that could potentially contain HTML. Unfortunately, there doesn't seem to be a jQuery method that will append the results of the .text() method to an element instead of replacing its contents.

Is there a way to append, instead of replace, this escaped text to an element? Or is there a better way to escape strings containing HTML?

Thanks.

- EDIT -

A little more context: I'm building an HTML string dynamically, and so I'll need to be able to add multiple elements with escaped content programmatically.

I'm used to using jQuery's .append() method to add text or HTML onto the end of a pre-existing element. I'm currently using jQuery's .text() to escape strings that could potentially contain HTML. Unfortunately, there doesn't seem to be a jQuery method that will append the results of the .text() method to an element instead of replacing its contents.

Is there a way to append, instead of replace, this escaped text to an element? Or is there a better way to escape strings containing HTML?

Thanks.

- EDIT -

A little more context: I'm building an HTML string dynamically, and so I'll need to be able to add multiple elements with escaped content programmatically.

Share Improve this question asked Aug 14, 2012 at 17:22 Nathan FriendNathan Friend 12.8k11 gold badges80 silver badges129 bronze badges 1
  • 2 You could always just escape the HTML separately, a la stackoverflow.com/questions/6020714/escape-html-using-jquery etc. – Dave Newton Commented Aug 14, 2012 at 17:26
Add a comment  | 

3 Answers 3

Reset to default 8

As I have tried many ways, I think the following method is the cleanest way to add text to whatever node you want. no stock tag needed, only plain text, which will help to avoid potential problems

$(document.createTextNode("SomePlainText")).appendTo(p);

You could create a dummy element to hold the result of .text() which can then be appended to your destination element:

$('<div/>').text('your <span>html</span> string').appendTo(...);

You could just use

$(whatever).text($(whatever).text() + whatever_you_want_to_append);

EDIT for the fiddle in my comment, try this:

for ( /* some looping parameters */ ) {
    $('<li></li>') // create an li
        .text(stringWithHtml) // pass it the text, as text not html
        .appendTo('#thisIsWhatINeed'); // append it where you want it
}

jsFiddle

发布评论

评论列表(0)

  1. 暂无评论