How can I replace or remove a wrapping div from markup with javascript or jquery and keep the dynamic contents in its place?

StackOverflow https://stackoverflow.com/questions/8946452

Question

I have an rss widget in place that is generating these weird divs that effect the layout of the blog post. These divs surround and image and only one paragraph of text pushing other paragraphs that should be wrapping around an image down, creating really awkward blocks of space.

Here is an example of the existing markup:

<div class="separator" style="clear: both; text-align: left;">
<a style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;" imageanchor="1" href="#" target="_blank">
<img width="320" height="214" border="0" src="http://3.bp.blogspot.com/-TIpzIZpEY50/TwEruI4XDlI/AAAAAAAAAXg/gIv3vafB3Sc/s320/December+2011+130.JPG">
</a>
and here is a bunch of text 
</div>

What I want to do is remove the wrapping div class separator and replace with the contents within. Each instance of this div has different content.

So I have tried to use the following jquery script but it doesn't work, because the content is not wrapped in child divs, so that is where I get stuck:

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){

$("div.separator").replaceWith(function() {
return $(this).contents();

});

Thanks for your help!

Was it helpful?

Solution

$("div.separator").children().unwrap();

OTHER TIPS

http://jsfiddle.net/Sztzq/

 ('.separator').children(':first').unwrap();

Just use jQuery's .unwrap() method:

$("div.separator").children(':first').unwrap();
$('div.seperator').each(function() {
  $(this).replaceWith($(this).children());
});

If you just want to remove them use $('div.separator').remove();.

To re-use the divs, use either

$('div.separator').empty().html('<p>your custom html here</p>');

or

$('div.separator').empty().append(yourExistingDOMElement);

depending on what you are replacing it with.

To tackle them all, it becomes:

$('div.separator').each(function () {
    $(this).empty().html(string); //or the append version.
});

Hope this helps,

Pete

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top