Add HTML escaped text: jQuery

I use the jQuery .append() method to add text or HTML to the end of a pre-existing item. I am currently using jQuery .text() to avoid strings that could potentially contain HTML. Unfortunately, there is no jQuery method that adds the results of the .text() method to an element instead of replacing its contents.

Is there a way to add this escaped text to the element instead? Or is there a better way to avoid strings containing HTML?

Thanks.

- EDIT -

A bit more context: I am building an HTML line dynamically, and therefore I need to be able to add multiple elements with screened content programmatically.

+6
source share
3 answers

You can create a dummy element to store the result .text() , which can then be added to your target element:

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

As I tried many times already, I think the following method is the cleanest way to add text to any node you want. no stock tag required, just plain text to avoid potential problems.

 $(document.createTextNode("SomePlainText")).appendTo(p); 
+8
source

You can just use

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

EDIT for the script in my comment, try the following:

 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

+1
source

Source: https://habr.com/ru/post/922862/


All Articles