JQuery: Get tag content excluding nested tags

断了今生、忘了曾经 提交于 2020-02-27 23:57:12

问题


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.


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/2007215/jquery-get-tag-content-excluding-nested-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!