views:

59

answers:

4

Hi all,

If I have html like this:

<li id="listItem">
    This is some text
    <span id="firstSpan">First span text</span>
    <span id="secondSpan">Second span text</span>
</li>

I'm trying to use .text() to retrieve just the string "This is some text", but if I were to say $('#listItem').text(), I get "This is some textFirst span textSecond span text".

Is there a way to get (and possibly remove, via something like .text("")) just the free text within a tag, and not the text within its child tags?

Thanks very much.

Clarification:

The HTML was not written by me, so this is what I have to work with. I know that it would be simple to just wrap the text in tags when writing the html, but again, the html is pre-written. Thanks.

A: 

just put it in a <p> or <font> and grab that $('#listItem font').text()

First thing that came to mind

<li id="listItem">
    <font>This is some text</font>
    <span id="firstSpan">First span text</span>
    <span id="secondSpan">Second span text</span>
</li>
Dorjan
I don't have control over putting the free text in tags, because the code I'm working off of was not created by me. If I could grab just that text, I could remove it and replace it with tags around it, or do anything I want. But again, the html is already pre-written.
Mega Matt
ah, ok. Then I think you're going to have to filter the results :Ssorry.
Dorjan
+1  A: 

It'll need to be something tailored to the needs, which are dependent on the structure you're presented with. For the example you've provided, this works:

$(document).ready(function(){
     var $tmp = $('#listItem').children().remove();
     $('#listItem').text('').append($tmp);
});

Demo: http://jquery.nodnod.net/cases/2385/run

But it's fairly dependent on the markup being similar to what you posted.

cpharmston
Perfect! Thanks!
Mega Matt
A: 

This untested, but I think you may be able to try something like this:

 $('#listItem').not('span').text();

http://api.jquery.com/not/

El Guapo
A: 

This seems like a case of overusing jquery to me. The following will grab the text ignoring the other nodes:

document.getElementById("listItem").childNodes[0];

You'll need to trim that but it gets you what you want in one, easy line.

gaoshan88