How to save jQuery from parsing pasted HTML?

Does anyone know how to stop jQuery fromparsing html that you insert before () and after ()? Let's say I have an element:

<div id='contentdiv'>bla content bla</div> 

and I want to wrap it like this:

 <div id='wrapperDiv'> <div id='beforeDiv'></div> <div id='contentDiv'>bla content bla</div> <div id='afterDiv'></div> </div> 

I am using the following jQuery / Javascript

 $('#contentDiv').each( function() { var beforeHTML = "<div id='wrapperDiv'><div id='beforeDiv'></div>"; var afterHTML = "<div id='afterDiv'></div></div>"; $(this).before(beforeHTML); $(this).after(afterHTML); } 

This, however, will not lead to proper packaging, it will create:

 <div id='wrapperDiv'> <div id='beforeDiv'></div> </div> <div id='contentDiv'>bla content bla</div> <div id='afterDiv'></div> 

Using wrap () will not work, as this causes jQuery to become even more confusing when used:

 $(this).wrap("<div id='wrapperDiv'><div id='beforeDiv'></div><div id='afterDiv'></div></div>"); 

How can i solve this?
Thanks in advance!

+4
source share
4 answers
 $('#contentDiv').each(function() { $(this).wrap('<div id="wrapperDiv">'); $(this).before('<div id="beforeDiv">'); $(this).after('<div id="afterDiv">'); }); 

gives:

 <div id='wrapperDiv'> <div id='beforeDiv'></div> <div id='contentDiv'>bla content bla</div> <div id='afterDiv'></div> </div> 
+10
source

your markup is not completed ... before and after you only need to take the nodes ...

what you are trying to do is wrap your content, which is different.

Do you want to:

.wrap (HTML);

http://docs.jquery.com/Manipulation/wrap#html

+2
source

I think you are approaching this wrong. Think about what you really want to achieve ...

You want WRAP all with one div. Then insert 1 div before and 1 div after.

do .wrap () first, then add before and after-divs relative to the content-div.

if you have the actual HTML as a string (from XHR or something else) then you need to read the html and combine it yourself, as Douglas Mail suggested.

+2
source

Sorry, but this should be obvious. In your case, you cannot use wrap because it attaches the original node to the deepest node that it finds in the HTML wrapping. You do not want this. Instead, read the HTML from your object and combine it with what you have:

 $('#contentDiv').each( function() { var beforeHTML = "<div id='wrapperDiv'><div id='beforeDiv'></div>"; var afterHTML = "<div id='afterDiv'></div></div>"; // This line below will do it... $(this).html(beforeHTML + $(this).html() + afterHTML); } 
0
source

All Articles