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.
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.
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.
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.
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.
$(
'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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With