Question

HTML:

<div class="featured">
    <h4><a href="#">Title 1</a></h4>
    <a href="#"><img src="image.png" class="image"/></a>
    <p><a href="#"></a><br />
    Description goes here</p>
</div>

<div class="featured">
    <h4><a href="#">Title 2</a></h4>
    <a href="#"><img src="image.png" class="image"/></a>
    <p><a href="#"></a></p>
    <p>Description goes here</p>
</div>

.. How do I strip out all <p> tags from .featured?

Thanks

Was it helpful?

Solution

This works, but only because your paragraph elements are at the end of your divs:

$(".featured p").each(function(){
    var content = $(this).html();
    $(this).parent().append(content);
    $(this).remove();
});

OTHER TIPS

Check out Ben Alman's unwrap "plugin"

$.fn.unwrap = function() {
  this.parent(':not(body)')
    .each(function(){
      $(this).replaceWith( this.childNodes );
    });

  return this;
};

your usage would be:

$(".featured p > *").unwrap();
$(".featured p").remove();

This works by changing each <p> to <span>. It does that in-place, so the <p>s don't have to be at the end (no append - it will not reorder the elements):

$(".featured p").replaceWith(function(){
     return $('<span />').html( $(this).html() );
});

It is using html, so the element will lose data and event bindings.

With jQuery 1.4 you could do it like this:

$(".featured p *").unwrap();
$(".featured p").each(function(){
  $(this).replaceWith("<span>"+ $(this).text() + "</span>")
});

Test it here

Text nodes don't get unwraped, so you have to do them separately. I'm not sure why replaceWith requires them to be inside tags.

Something like this?

$(".featured p").each(
  function(){
    $(this).after($(this).html()).remove();
});

Edit 2: Tested, works. nice and simple.

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