Need Jquery Text() Function To Ignore Hidden Elements
Hello
Solution 1:
Filter the elements using .filter(":visible")
.
Or use this:
$("#test :visible").text();
But the jQuery documentation advises us to use .filter()
instead:
Because :visible
is a jQuery extension and not part of the CSS specification,
queries using :visible
cannot take advantage of the performance boost provided by the native DOM querySelectorAll()
method. To achieve the best performance when using :visible to select elements, first select the elements using a pure CSS selector, then use .filter(":visible")
.
Solution 2:
Use :visible
in your selector as such:
$("#test > p:visible").text()
A Function example:
-- Edit:
http://jsfiddle.net/8H5ka/ ( Works on Chrome it displays "Hello" in Result )
If the above doesn't work:
Solution 3:
If space isn't a major concern you could copy the markup, remove the hidden elements, and output that text.
var x = $('#test').clone();
x.filter(':not(:visible)').remove();
return x.text();
Solution 4:
I had this problem and found this question, and it seems the actual solution is based on the provided answers but not actually written out. So here's a complete solution that worked for my situation, which is the same as the OP with the additional provision that elements may be invisible due to external styles based on DOM position. Example:
<style>.invisible-childrenspan { display: none; }</style><divclass="invisible-children"><divid="test">Hello <span>Goodbye</span></div></div>
The solution is to:
- Make a clone of the entire object.
- Remove invisible objects in place; if we take
#test
out of the DOM before we remove invisible objects, jQuery might not know they're invisible because they will no longer match the CSS rules. - Get the text of the object.
- Replace the original object with the clone we made.
The code:
var$test = $('#test');
// 1:var$testclone = $test.clone();
// 2: We assume that $test is :visible and only remove children that are not.$test.find('*').not(':visible').remove();
// 3:var text = $test.text();
// 4:$test.replaceWith($testclone);
// Now return the text...return text;
// ...or if you're going to keep going and using the $test variable, make sure// to replace it so whatever you do with it affects the object now in DOM and// not the original from which we got the text after removing stuff.$test = $testclone;
$test.css('background', 'grey'); // For example.
Solution 5:
Here is how I did it with MooTools:
$extend(Selectors.Pseudo, {
invisible: function() {
if(this.getStyle('visibility') == 'hidden' || this.getStyle('display') == 'none') {
returnthis;
}
}
});
Element.implement({
getTextLikeTheBrowserWould = function() {
var temp = this.clone();
temp.getElements(':invisible').destroy();
return temp.get('text').replace(/ |&/g, ' ');
}
})
Post a Comment for "Need Jquery Text() Function To Ignore Hidden Elements"