views:

548

answers:

5

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

+1  A: 
$(".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.

Kobi
+1, bah, beat me by 16 seconds.
karim79
this will definitely work...
Ruchir Shah
But this way, you'll delete also it's contents, as I understand it, he wants just to strip the tags out.
Adam Kiss
exactly. I want to strip the tags only, not content.
Nimbuz
A: 

Something like this?

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

Edit 2: Tested, works. nice and simple.

Adam Kiss
Hmm...it has no effect.
Nimbuz
-1 html() returns string, not a jQuery object.
Anton
Well, it was written just as an idea, not solution, i haven't tested it.
Adam Kiss
Downvotes for what? :O
Adam Kiss
I still think this is closest to requirements :P No spans included, tested(finally), just strips out wrapper (in this case `<p>`) :]
Adam Kiss
+2  A: 

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();
});
karim79
`.text()` won't return you children tags.
Adam Kiss
@Adam Kiss - true, changed it to html() instead. Not sure if that warranted a down-vote though :)
karim79
Deleted downvote - it does not work :) Now it does - but look at my (edited) code though :) tested, does not `append()`, but `after()`, so it's in place of deleted `<p>`.
Adam Kiss
+1  A: 

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.

Sam Hasler
+1  A: 

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();
PetersenDidIt