DNS
DNS

Reputation: 38199

What's the most efficient way to append elements while also escaping text, using jQuery?

I'm optimizing a bottleneck that, not surprisingly, is the result of tens of thousands of appends in a loop.

I'm familiar with the pattern of accumulating new elements as strings, then joining and inserting them in a single append. But what if those elements have text content that needs to be escaped, i.e. would normally be set using .text()?

I'm currently creating these as separate elements, appending them to a container outside the DOM, then inserting that container. Is there a faster approach?

Upvotes: 0

Views: 90

Answers (1)

N Rohler
N Rohler

Reputation: 4615

Use the accumulation-as-string method. If you need to simulate the text() method, use the shown escapeText method like this:

var escapeText = function(s)
{
   return s.split('&').join('&amp;').split('<').join('&lt;').split('>').join('&gt;').split('"').join('&quot;');
};

var someArray = ....
var toInsert = '';
for (var i=0; i<someArray.length; i++)
{
   toInsert += '<p>' + escapeText(someArray[i]) + '</p>';
}
$('#foo').append(toInsert);

Upvotes: 1

Related Questions