Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove an element but not its content with javascript?

I have a string which is a simple <a> element.

var str = '<a href="somewhere.com">Link</a>'

Which I want to turn into:

Link

I can remove the </a> part easily with str.replace("</a>", "")but how would I remove the opening tag <a href="somewhere.com>?

like image 446
Weblurk Avatar asked Mar 19 '26 17:03

Weblurk


2 Answers

Use unwrap like

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

But it work with the elements that are related to DOM.For your Better solution try like

 str = ($(str).text());

See this FIDDLE

like image 59
Gautam3164 Avatar answered Mar 22 '26 07:03

Gautam3164


This will strip the whole tag:

str.replace(/<[^>]+>/g,'');

And this just the first part:

str.replace(/<[^/>]+>/g, '');
like image 40
jazZRo Avatar answered Mar 22 '26 06:03

jazZRo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!