5

I'm a bit tired tonight and just can't really think how to do this simply. Basically, I have something similar to the below and I want to strip out html tags but leave their contents:

<a href="#">some content</a> and more <a href="#"> and more content</a>

and actually return the following:

some content and more and more content

Any help as always - massively appreciated!

EDIT: Thank you all so much for the answers - there I was going down the regular expression route, way to over complicate things! I actually ended up using .text() as suggested below, I've used this before but only to set, never to retrieve and it worked better as I was returning quite a large object! Thank you so much for all the suggestions :). I'll accept the answer after 6 minutes.

Jamie
  • 1,004
  • 1
  • 14
  • 32

5 Answers5

11

$('a').contents().unwrap()

Fiddle

JGrinon
  • 1,453
  • 1
  • 14
  • 36
user113716
  • 318,772
  • 63
  • 451
  • 440
4

$(selector).text() should strip out all the html.

jacobangel
  • 6,896
  • 2
  • 34
  • 35
  • Never knew this method stripped out the tags by default! I've only ever used it to set text, or retrieve plain text, thank you so much for opening my mind! – Jamie May 17 '11 at 21:12
2

This way is a little longer but maybe more self explanatory than the contents() method.

$('a').each(function () {
    $(this).replaceWith($(this).html())
})

replaceWith accepts replacement html. (not selectors)

700 Software
  • 85,281
  • 83
  • 234
  • 341
2

You can write

$(...).find('*')
      .replaceWith(function() { return this.childNodes });

I don't know how well this will handle nested tags.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

Perhaps something like this:

jQuery.fn.stripTags = function() {
    return this.replaceWith( this.html().replace(/<\/?[^>]+>/gi, '') );

};

Source: http://www.mail-archive.com/jquery-en@googlegroups.com/msg18843.html

George Cummins
  • 28,485
  • 8
  • 71
  • 90