views:

401

answers:

2

I've got some HTML like the following:

<span id="A">Text I'm interested in
  <span id="B">Other crap I don't care about</span>
</span>

I'm looking to get the text content of span "A" excluding any nested tags (i.e. the content of span "B" in the above example). I'm trying to get the text content, not the HTML content. Also, in my particular case, I know there will always be some text inside of span A prior to any other tags, but I'm interested in the less-constrained solution as well.

The simple-but-clunky approach I've considered going with is just doing $("#A").html() and then parsing through until I hit an unescaped "<" but it feels like there should be a cleaner solution.

A: 

The following should get it for you

$("#A").find("#B").remove().end().text());

This is very specific to your problem. Not sure if there's a generic solution, though

James Wiseman
He doesn't want the content of the second span, so this won't work as it gives all the plain text inside the #A
Erik
Realised that as soon as I posted. Edited with correct code
James Wiseman
This one had me scratching my head, too. See my revised solution above :)
Erik
+3  A: 

I'm fairly sure there's no built in way to do it - although you could look for a plugin, it may exist. Someone else posted the .text() method (but deleted the post) which will get you ALL the text, minus the tags, which means you'll get "Text I'm interested in Other crap I don't care about" -- not what you want.

EDIT

Okay, I decided I was interested in this so I spent some time. Here's the solution :)

    copyOf = $('#A').clone();
    copysKids = copyOf.children();
    copysKids.remove();

    alert(copyOf.text());

What we're doing is making a clone of the node you're trying to get text out of - we don't want to operate on the original because this would change the page. Then we're grabbing a collection of all the child nodes, and nuking them. The remaining text is the text you were looking for.

Erik
+1 - I think this is the right answer, I was about to go there but decided against it due to laziness.
altCognito
I thought there would be some sort of "set subtraction" solution, but I'm new to jQuery. This fits the bill perfectly. Thanks!
db
This will bulky in the case of large node trees, but it works.
altCognito
A quick note for DB - I just realized since this gets rid of ALL children ... if there's, say, bold text in there ... that text will be zapped too, since <b> is a subtag. You could always loop over copysKids and look so see what tags they are before deciding to delete or not.
Erik
That's a good point, Erik. I hadn't thought of that, but thankfully, that won't be a problem where I'm actually applying this.
db