Get only visible text with jquery

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

Lets say I have some html like this:

FoohiddenBar

In

3条回答
  •  走了就别回头了
    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

提交回复
热议问题