Skip to content

Instantly share code, notes, and snippets.

@TALlama
Created July 29, 2012 01:54
Show Gist options
  • Save TALlama/3195685 to your computer and use it in GitHub Desktop.
Save TALlama/3195685 to your computer and use it in GitHub Desktop.
A jQuery extension to return only the visible text in a node.
jQuery.fn.visibleText = function() {
if (this.length === 0) return null;
if (this.length > 1) return this.first().visibleText();
if (this[0].nodeType === 3) return this.text();
var buffer = [];
$.each(this.contents(), function(ix, e) {
if ($(e).is(':visible')) {
return buffer.push($(e).visibleText());
}
});
buffer.join('');
};
@NicHoza
Copy link

NicHoza commented Jan 2, 2014

Your function seems to have quite a few problems. Wouldn't something like this work better?

    $.fn.visibleText = function() {
      if (this.length === 0)
            return '';

      if (this.length === 1 && this[0].nodeType === 3)
            return this.text();

      var visibleText = '';

      $.each(this.contents(), function(index, element) {
        var theElement = $(element);

        if (theElement.is(':visible'))
          visibleText += theElement.visibleText();
      });

      return visibleText;
    };

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment