jquery: how can you select texts not surrounded by html tags?

后端 未结 7 2234
Beer

Vodka
rum
whiskey

how can you select beer ? or rum ? in jquery ? they are not surrounded by any html tags....

7条回答
  •  孤城傲影
    2021-01-18 16:07

    If you mean that you want to select the text node directly, this is advised against using jQuery. To clarify, getting a wrapped set of text nodes is not a problem, but chaining commands onto a wrapped set of text nodes has unpredictable results or does not work with many of the commands since they expect the wrapped set to contain element nodes.

    You can do it by filtering the children of a parent to return only text nodes, i.e. nodeType === 3 but if your question is about performing some manipulation on the text, then get the parent element and manipulate the text contents. For example,

    $('#parentElement').html(); // html of parent element
    
    $('#parentElement').text(); // text content of parent element and any descendents
    
    $('#parentElement').contents(); // get all child nodes of parent element
    

    If you wanted to get the text nodes, the following is one way

    $('#parentElement').contents().filter(function() { return this.nodeType === 3 });
    

    Or you may want to look at Karl Swedberg's Text Children plugin, which provides various different options too.

    EDIT:

    In response to your comment, one way to work with the text nodes in a wrapped set is to convert the jQuery object to an array, then work with the array. For example,

    // get an array of the immediate childe text nodes
    var textArray = $('#parentElement')
                        .contents()
                        .filter(function() { return this.nodeType === 3 })
                        .get();
    
    // alerts the text content of each text node
    $.each(textArray, function() {
        alert(this.textContent);
    });
    
    // returns an array of the text content of the text nodes
    // N.B. Remember the differences in how  different 
    // browsers treat whitespace in the DOM
    textArray = $.map(textArray, function(e) {
        var text = $.trim(e.textContent.replace(/\n/g, ""));
        return (text)? text : null;
    });
    

提交回复
热议问题