Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove span tag in string using jquery

Tags:

How to remove span tag from string using jquery? I have multiple span tag in string variable

     <p>No Change<span style="color: #222222;">&nbsp;</span> I love cricket<span style="color: #222222;">Cricket cricket&nbsp;</span></p> 
like image 999
Ali Avatar asked Feb 01 '12 09:02

Ali


People also ask

How to remove span tag in jquery?

find('span'). remove();

How do I remove a span tag?

Inline text styles are often set by using the span tags. Activating this option will remove all span tags including their styles, classes etc.

How do I remove a class from Span?

To unwrap the element and keep its content, right-click on the element (or select More actions from the selected element menu) to open the context menu and there select Transform -> Remove outer span.


2 Answers

If this is definitely just stored as a string you can do the following...

var element = $(myString);//convert string to JQuery element element.find("span").remove();//remove span elements var newString = element.html();//get back new string 

if in fact this is already rendered html in your page then just do...

$("span").remove();//remove span elements (all spans on page as this code stands) 

If you want to keep the contents of the span tag you can try this...

var element = $(myString);//convert string to JQuery element element.find("span").each(function(index) {     var text = $(this).text();//get span content     $(this).replaceWith(text);//replace all span with just content }); var newString = element.html();//get back new string 

Here is a working example (you will see two alerts: string at start, string at end)


You can also just do this which might get the result you need:

var justText = $(myString).text(); 
like image 122
musefan Avatar answered Oct 19 '22 08:10

musefan


This way you can keep inner text of the span by using .contents() jquery method (example of my code below):

$('#navc-22 > a > span').contents().unwrap(); 
like image 41
estinamir Avatar answered Oct 19 '22 08:10

estinamir