Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep jQuery from parsing inserted HTML?

Does anyone know how to stop jQuery fromparsing html you insert through before() and after()? Say I have an element:

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

and I want to wrap it in the following way:

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

I use 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 result in the correct wrapping, it will create:

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

Using wrap() won't work either since that gets jQuery even more mixed up when using:

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

How should I solve this?
Thanks in advance!

like image 322
Pim Jager Avatar asked Dec 09 '22 22:12

Pim Jager


1 Answers

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

produces:

<div id='wrapperDiv'>
    <div id='beforeDiv'></div>
    <div id='contentDiv'>bla content bla</div>
    <div id='afterDiv'></div>
</div>
like image 136
Owen Avatar answered Dec 15 '22 00:12

Owen