Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove tag but leave contents - jQuery/Javascript

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.

like image 256
Jamie Avatar asked May 17 '11 21:05

Jamie


People also ask

What is the difference between remove () and detach () methods in jQuery?

remove() removes the matched elements from the DOM completely. detach() is like remove() , but keeps the stored data and events associated with the matched elements.

How remove and append in jQuery?

jQuery uses: . append(); and . remove(); functions to accomplish this task. We could use these methods to append string or any other html or XML element and also remove string and other html or XML elements from the document.

What is the opposite of remove in jQuery?

version added: 1.4. The . detach() method is the same as . remove() , except that . detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

How do I remove a tag from a string?

The HTML tags can be removed from a given string by using replaceAll() method of String class. We can remove the HTML tags from a given string by using a regular expression. After removing the HTML tags from a string, it will return a string as normal text.


3 Answers

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

Fiddle

like image 102
user113716 Avatar answered Oct 30 '22 07:10

user113716


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

like image 27
jacobangel Avatar answered Oct 30 '22 08:10

jacobangel


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)

like image 40
700 Software Avatar answered Oct 30 '22 08:10

700 Software