FoohiddenBarT...">

Get only visible text using jquery

Suppose I have html, for example:

<div id="content">Foo<span style='display:none'>hidden</span>Bar</div> 

This is actually more complicated and generated using angular using ng-hide and the like. I need to get all the text from div content that is displayed to the user. In this case, I would like to get a FooBar .

$('#content').text() is the closest I found, but it gives me a FoohiddenBar in this case. Is there a good way to get only the visible content of a div? I really need a text() function that skips hidden elements.

+4
source share
3 answers

create a clone, add it to the DOM (as indicated by Slindberg), delete 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

+8
source

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

The only way I found this is to actually flip all nodes from top to bottom by dropping visually hidden nodes. Fortunately, this can be expressed in a rather compressed 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 that the root element of the selector is not node text (which almost never happens). Also note that $(el).text() can be replaced with el.textContent if you do not need to support IE8.

Jsfiddle

+5
source

The trick is to change the DOM in place to get the text, and then bring it back to the original when we are 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 the cloned objects are invisible until they are inserted into the DOM. By modifying the DOM in place, we avoid this problem.

0
source

Source: https://habr.com/ru/post/1492379/


All Articles