How to get text inside of container that is not part of children

后端 未结 3 1132

Let\'s have html code like this:

1.Hallo Kitty,
How are you?
<
相关标签:
3条回答
  • 2021-01-06 06:26

    this will work for you

    $('#d1')
      .contents()
      .filter(function() {
        return this.nodeType == Node.TEXT_NODE;
    }).text()
    

    or you can use this as suggested below for old browser support also

    var text = $("#d1").contents().filter( function() {
        return this.nodeType === 3;
    }).text();
    

    Demo

    0 讨论(0)
  • 2021-01-06 06:28

    http://jsfiddle.net/SGZW4/

    var text = $("#d1").contents().filter( function() {
        return this.nodeType === 3;
    }).text();
    
    0 讨论(0)
  • 2021-01-06 06:33

    Improving on halex's trick, you can take advantage of the fact that .children() finds only DOM nodes and ignores text nodes:

    var text = $('#d1').clone().children().remove().end().text(); // string "Hallo "
    

    ...but I prefer the .nodeType technique, because it's more clear what you're doing.

    0 讨论(0)
提交回复
热议问题