最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Remove tag but leave contents - jQueryJavascript - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited May 17, 2011 at 21:11 Jamie asked May 17, 2011 at 21:01 JamieJamie 1,0141 gold badge14 silver badges35 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 11

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

Fiddle

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

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)

You can write

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

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

Perhaps something like this:

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

};

Source: http://www.mail-archive.com/[email protected]/msg18843.html

发布评论

评论列表(0)

  1. 暂无评论