0

I have some html that is in the form

<span class="prefix">something</span> (Optional)
Text
<span class="badge">Something else</span> (optional, can be multiple)
<span class="postfix">Another thing</span>

And I want to wrap the Text, but not the spans, in another span so that I can extract and replace it using jQuery as necessary. I can't edit the back end code that is generating this HTML. Given that I don't know in advance whether the first span will be there, or how many spans there will be at the end, is there any way to wrap the plain text so that it can be operated on?

I am hoping to get an output that looks something like this:

<span class="prefix">something</span>
<span class="txt">Text</span>
<span class="badge">something else</span>...
<span class="postfix">another thing</span>
JackW
  • 999
  • 11
  • 22
  • _"I am hoping to get an output that looks something like this:"_ Is requirement to wrap text within existing `span` elements with an additional `span` element ? Or, include existing text of `span` elements within `.txt` `span` ? – guest271314 Jul 11 '15 at 14:55
  • @guest271314 To wrap the plain text (not inside any other nodes) with a new span. – JackW Jul 11 '15 at 14:59

2 Answers2

2

Try this:

$('#container').contents()
               .filter(function() { return this.nodeType === 3 })
               .wrap('<span class="txt" />');

Based on this answer: https://stackoverflow.com/a/5291776/616535

Community
  • 1
  • 1
Andrey Etumyan
  • 1,394
  • 11
  • 17
1
  1. filter() the contents() of the container element to those that are pure text nodes
  2. wrap() them in a span

$('#container').contents().filter(function() {
  return $(this)[0].nodeValue && $(this)[0].nodeValue.trim();
}).wrap('<span class="txt"/>');
.txt{
  color:green;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="container">
  <span class="prefix">something</span>
  Text
  <span class="badge">Something else</span> 
  <span class="postfix">Another thing</span>
</div>
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53