I’m trying to create a javascript function that receives a string that is assumed to be HTML and removes all elements which would not be visible. I’m not operating on the page here, just a string of HTML from anywhere.
At first it seemed using the :hidden selector would have been ideal, but I couldn’t get that to work. So I started playing with filter(), but haven’t had success.
function StripInvisibleNodes(html) {
var container = "" + html+ "";
//var $onlyvisiblehtml = $(container).find(":hidden").remove(); // didn't work
var $onlyvisiblehtml = $(container).find('*').filter(function() { return this.style.display == "none"; }).remove();
var removed = $onlyvisiblehtml.html();
return removed;
}
Update: the following is the working solution
function StripInvisibleNodes(html) {
$('body').append("<div id='tempspace' style='visibility:hidden'>" + content + "</div>");
var $toremove = $('#tempspace').find("*").filter(':hidden');
$toremove.remove();
var resultstring = $('#tempspace').html();
$('#tempspace').remove();
return resultstring;
}
No HTML is considered
:visibleby jQuery if it’s not been rendered in the DOM. For instance:will produce an empty jQuery object.
What you can do is render them briefly in the DOM, compute which elements are visible, and then remove them immediately. You can put them inside an element with
visibility: hiddenoropacity: 0if you don’t want to risk it blinking into view:HTML:
http://jsfiddle.net/4NxBd/2/