0

I have this HTML:

<div class="one">32<span class="one_span"> Years old</span></div>

I want to be able to select the class one text without the span's text. Is that possible? Here's what I've tried, but it didn't work

 var age = $('.one:not(.one_span)').text(); 
user3541436
  • 95
  • 1
  • 8

5 Answers5

4

Use contents():

var age = $('.one').contents()[0]

Here's a fiddle to demonstrate.

contents(): Get the children of each element in the set of matched elements, including text and comment nodes.

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
1

You can you parseInt, JSFiddle: http://jsfiddle.net/4qT4u/

pavel
  • 26,538
  • 10
  • 45
  • 61
1
var text = $(".one")
    .clone()    //clone the element
    .children() //select all the children
    .remove()   //remove all the children
    .end()  //again go back to selected element
    .text()

Removes all child elments, and sets text to the remaining content.

Working fiddle: http://jsfiddle.net/G9SfB/ Source: http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/

circusdei
  • 1,967
  • 12
  • 28
1

To be safe, clone the div, remove the span from the clone,and get the text from that:

var cl = $('div.one').clone();
cl.find('span').remove();
var age = cl.text();
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
0

Found here: https://stackoverflow.com/a/11348383/1524085

var text = $('div').contents(':not(.one_span)').text();

http://jsfiddle.net/6pRS3/

Community
  • 1
  • 1
Pedro Estrada
  • 2,384
  • 2
  • 16
  • 24