2

I have a span that contains text that I would like to use. But within this span there is a h2 that I want to ignore. (This isnt my mark up and I cant change this so moving the h2 outside of the span is not an option)

Here is the mark up:

<span>
<h2>Joe Bloggs</h2>
Executive Director
</span>

Here is my current code which is getting the contents of the span including the h2

currentLi = $('ul#example2 li.frame3');

position = $(currentLi).find('span').text();

So my hopeful outcome will be the variable position containing the text "Executive Director"

Cecil Theodore
  • 9,549
  • 10
  • 31
  • 37
  • 1
    duplicate of: http://stackoverflow.com/questions/6925088/get-the-text-after-span-element-using-jquery and/or http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery and/or http://stackoverflow.com/questions/4154171/how-to-get-a-bit-of-text-using-jquery – Chad Dec 21 '11 at 14:04
  • IMHO it's not a strict duplicate of any of these - this one is asking for everything except specifically an H2 child node – Alnitak Dec 21 '11 at 14:14

5 Answers5

3

Clone the span, remove the <h2>, and get the remaining text.

var clone = $(document).find('span').clone();
$(clone).find('h2').remove();

var position = $(clone).text().trim();

Working demo at http://jsfiddle.net/ukFWq/

Alnitak
  • 334,560
  • 70
  • 407
  • 495
3

How about using filter with .contents. Inside the filter function you can evaluate the nodeType property, ensuring that it is 3 (text nodes only):

var onlySpan = $("span").contents().filter(function () {
    return this.nodeType === 3;
}).text().trim();

Example: http://jsfiddle.net/Wp4FR/

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
0

this is something which i will never suggest you, but as per your requirement following code can work.

    var index = position.indexOf('</h2>');
    position = position.substring(index+5, position.length)
    alert(position); 
Murtaza
  • 3,045
  • 2
  • 25
  • 39
0

The best is to use the textchildren plugin

You can find a demo in this jsfiddle

All you have to do is to use the plugin like this

$('span').textChildren()
Bouchaala Sabri
  • 647
  • 4
  • 9
0

you can also use the not filter.

currentLi = $('ul#example2 li.frame3');

position = $(currentLi).find('span:not(h2).text()').text();

you might be able to do it with a not method as well

span.not(h2)
Brian
  • 2,229
  • 17
  • 24