Rich-text Reply

Append HTML: Which code is better: append + replace with or append directly?

miguelm 03-17-16
Accepted Solution

Append HTML: Which code is better: append + replace with or append directly?

[ Edited ]

Hi!

 

When you insert HTML by the Optimizely visual editor, the code created appends a div, and after that the div is replaced by the content that you want to insert. Why is not appending the content directly?

 

What Optimizely does:

$("body").append("<div id=\"optimizely_935759238\">...</div>");
$("#optimizely_935759238").replaceWith("<div id=\"optimizely_935759238\">The HTML code that I want to append</div>");

Why is not appending the code directly?

$("body").append("<div id=\"optimizely_935759238\">The HTML code that I want to append</div>");

Thank you

 

Level 2

robertchan 03-17-16
 

Re: Append HTML: Which code is better: append + replace with or append directly?

Neither is optimal. For some basic html, you should be creating it as a string like so:

 

var newString = [
   '<div id="newDiv">',
   'This is a new div',
   '</div>'
].join('');

//New div created

$(newString).appendTo('.someClass');

//Append your new div to some class
Robert Chan

Experimentation Hero
miguelm 03-17-16
 

Re: Append HTML: Which code is better: append + replace with or append directly?

Thank you @robertchan !

 

Level 2
robertchan 03-17-16
 

Re: Append HTML: Which code is better: append + replace with or append directly?

Anytime!
Robert Chan

Experimentation Hero