开发者

JQuery: Get tag content excluding nested tags

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开发者_StackOverflow社区'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.


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.


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


For the OP's specific example, the correct solution would be

$('#A').prop('firstChild').nodeValue

This would have to be elaborated a bit if you wanted a robust solution that would handle a situation where one or more of the first N children were tags instead of text nodes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜