Finding text node

前端 未结 8 1355
半阙折子戏
半阙折子戏 2021-01-03 08:14

Is there a clever jQuery selector for selecting a text node like this:

one two three
8条回答
  •  长情又很酷
    2021-01-03 08:36

    Here is how to select text nodes using jQuery:

    var x = $('div') 
      .contents() 
      .filter(function() { 
        return this.nodeType == 3;
        //return this.nodeType == Node.TEXT_NODE;  this works unless using IE 7
      }); 
    

    In your example x will then contain 'one' at index 0 and 'three' at index 1. Like Keith Rousseau said, you can't really just grab that text, but if you know it will be last you can get it like this:

    var elemThree = x[x.length-1];
    

    You can also add the strong tag like this:

    $(x[x.length-1]).wrap("");
    

    This questions describes selecting text nodes with jQuery (my first code snippet).

提交回复
热议问题