Skip to content Skip to sidebar Skip to footer

Jquery Replacewith Not Working

Using Jquery 1.7.1 I have two divs
{page content here}
Those show up in the page sour

Solution 1:

First i want to site that you're a producing an incorrect structure of DOM. If your script will run it will looks like this:

<div class="highlightStart"><section></div>
{page content here}
<div class="highlightEnd"></section></div> 

and this is not a good structure if you want have:

<section>
{page content here}
</section>

Should be something like this:

Your DOM:

<div id="content">
{page content here}
</div>

And in your script:

$(document).ready(function () {
  content = $('#content').text();

  $('#content').html($('<section>').text(content));
});

Please see myfiddle for reference

Solution 2:

The replaceWith method expects entire elements, not tags. You'll need to wrap your page contents with a new element, then remove the two original divs.

Update: This might get you close:

$(document).ready(function () {
   $('.highlightStart').nextUntil('.highlightEnd').andSelf()
       .wrap('<section class="highlight"></section>');

    $('.highlightStart, .hightlightEnd').remove();
});

http://jsfiddle.net/isherwood/H36UE

Something's off a bit with this, but I'm out of time. Good luck.

Solution 3:

Based on help from isherwood, used this as the solution:

http://jsfiddle.net/H36UE/1/

With HTML tree like this:

<div><div><divclass="highlightStart">highlightStart</div></div></div><div>Outside<div>Content to Highlight</div>More</div><div>second</div><div>third</div><div><div><divclass="highlightEnd">highlightEnd</div></div></div>

This Javascript:

$(document).ready(function () {
  $('.highlightStart').parent().parent().replaceWith("<div class='highlightStart'>");
  $('.highlightEnd').parent().parent().replaceWith("<div class='highlightEnd'>");
  $('.highlightStart').nextUntil('.highlightEnd').andSelf().wrapAll("<section class='highlight'>");

 $('.highlightStart, .highlightEnd').remove();
});

Post a Comment for "Jquery Replacewith Not Working"