Finding text node

前端 未结 8 1258
半阙折子戏
半阙折子戏 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:29

    CSS can't select text nodes

    jQuery uses css3 selectors that only select elements. To get the desired effect, you'll need to do the following:

    var div = $('find the div')[0];
    var txtNode = div.lastChild
    var str = document.createElement('strong')
    str.appendChild(txtNode) //removes the text node from the dom.
    div.appendChild(str)
    
    0 讨论(0)
  • 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("<strong></strong>");
    

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

    0 讨论(0)
  • 2021-01-03 08:39

    Check out this jQuery highlight plugin: http://tinyurl.com/6rk6ae

    It might not do exactly what you want, but the source contains good examples of working with text nodes and efficiently modifying the DOM around them.

    0 讨论(0)
  • 2021-01-03 08:42

    Not without some programming. If your main DIV had an ID or class, you could do this:

    var html = $("#my_div").html();
    var array = html.split("</span>");
    array[1] = "<strong>" + array[1] + "</strong>";
    html = array[0] + "</span>" + array[1];
    
    $("#my_div").html(html);
    
    0 讨论(0)
  • 2021-01-03 08:45

    I'm not sure you can easily do that with straight jQuery, unless you can wrap that word in another tag when writing it out. You could resort to regular expressions, something like:

    function wrapWithTag(tagname, element, text)
    {
        var html = element.html();
        var rx = new RegExp('(' + text + ')', "gi");
    
        element.html(html.replace(rx, '<' + tagname + '>$1</' + tagname + '>'));
    }
    
    $(function(){
        wrapWithTag('strong', $('div'), 'three');
    });
    

    The regular expression will need some tuning if you're trying to match text in different places within the element though.

    0 讨论(0)
  • 2021-01-03 08:49

    Is there a reason why you can't wrap three in some html element when you are generating the markup? It isn't really possible to grab some random word from the text and wrap it - unless you know it will always be the absolute last word in the div. If so you could do this to get the word:

    var txt = $(div).text();
    var txtArr = txt.split();
    var wordToWrap = txtArr[txtArr.length - 1];
    
    0 讨论(0)
提交回复
热议问题