5

I wonder, how to delete:

<span>blablabla</span>

from:

<p>Text wanted <span>blablabla</span></p>

I'm getting the text from p using:

var text = $('p').text();

And for some reason I'd like to remove from var text the span and its content.

How can I do it?

3 Answers 3

5

It's impossible to remove the <span> from the variable text, because it doesn't exist there — text is just text, without any trace of elements.

You have to remove the span earlier, while there is still some structure:

$('p').find('span').remove();

Or serialize the element using HTML (.html()) rather than plain text.

Don't edit HTML using regular expressions — HTML is not a regular language and regular expressions will fail in non-trivial cases.

var html = $('p').html();

var tmp = $('<p>').html(html);
tmp.find('span').remove();

var text = tmp.text();
Sign up to request clarification or add additional context in comments.

2 Comments

I didn't want to delete the span node from DOM. I needed the text from p (in variable) without span and its content.
@sunpietro In that case you could walk p.childNodes and concatenate their .textContent, skipping nodes with .tagName=='SPAN' (that's raw DOM, I'm not sure what that is in jQueryish).
3
text = text.replace(/<span>.*<\/span>/g, '');

3 Comments

Beware, if you're not the one authoring the HTML, the HTML may contain <span attributeName="blah" otherAttribute="blahblah"..>. Only use regex on HTML if you're completely in control of the HTML.
Well, OP asked about removing <span>blablabla</span> and nothing else :) If there is possibility of having something more complex we need to remove, the regex will be more complex.
Yep, I'm just warning the OP. He wasn't too clear about what to expect in the <span..> tag. And he didn't specify if he was in control of the HTML.
2

to remove the unwanted whitespace before the <span> use

text = text.replace(/\s*<span>.*<\/span>/g, '');

leaving you with

<p>Text wanted</p>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.