Get only visible text with jquery

前端 未结 3 1869
死守一世寂寞
死守一世寂寞 2021-01-13 16:53

Lets say I have some html like this:

FoohiddenBar

In

相关标签:
3条回答
  • 2021-01-13 17:36

    The trick is to modify the DOM in place to get the text, and then revert it back to the original when we're done with it. The following does the trick:

    function get_visible_text(content) {
        // Not so easy to get the visible text
        var saved = $(content).clone();
        // Remove the hidden parts
        $(content).find(':hidden').remove();
        // Get the remaining text
        var visible_text = $(content).text();
        // Now revert back to our saved version
        $(content).replaceWith(saved);
        return visible_text;
    }
    

    Note that @slindberg is correct, @adeneo's answer will not work because cloned objects are invisible until they are inserted into the DOM. By modifying the DOM in place, we avoid that problem.

    0 讨论(0)
  • 2021-01-13 17:42

    Unfortunately @adeneo's answer won't work in most cases, since cloning creates a document fragment whose children are by definition not visible (they are not attached to the document) and are therefore all removed before .text() is called. This means that text of the element's children won't be included in the result.

    The only way I've found to do this is to actually traverse all nodes top-down, omitting visually hidden nodes. Fortunately this can be expressed in a fairly concise plugin:

    jQuery.fn.visibleText = function() {
      return $.map(this.contents(), function(el) {
        if (el.nodeType === 3) {
          return $(el).text();
        }
        if ($(el).is(':visible')) {
          return $(el).visibleText();
        }
      }).join('');
    };
    

    Note that this plugin assumes the selector's root element is not a text node (which is almost never the case). Also note that $(el).text() can be replaced with el.textContent if you don't have to support IE8.

    JSFiddle

    0 讨论(0)
  • 2021-01-13 17:46

    create a clone, add it to the DOM (as pointed out by slindberg), remove all hidden elements, and then get the text :

    var clone = $('#content').clone();
    
    clone.appendTo('body').find(':hidden').remove();
    
    var text = clone.text();
    
    clone.remove();
    

    FIDDLE

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