lilWebbie
lilWebbie

Reputation: 33

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

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!

Upvotes: 3

Views: 1139

Answers (5)

Mark Schultheiss
Mark Schultheiss

Reputation: 34217

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

Upvotes: 1

Bassam Mehanni
Bassam Mehanni

Reputation: 14944

$('div.seperator').each(function() {
  $(this).replaceWith($(this).children());
});

Upvotes: 1

pete
pete

Reputation: 25091

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

Upvotes: 0

maxedison
maxedison

Reputation: 17573

Just use jQuery's .unwrap() method:

$("div.separator").children(':first').unwrap();

Upvotes: 1

mrtsherman
mrtsherman

Reputation: 39892

http://jsfiddle.net/Sztzq/

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

Upvotes: 1

Related Questions