I’m far from a JavaScript expert but I’m trying to migrate some mootools code to jQuery but am struggling!
I have a web form which contains several tables with a css class of ‘.table-row’. Upon clicking a button, I’d like to find all the rows which have ‘.table-row’ and if their display property is set to none, I’d like to remove them from the page before submitting.
This is my mootools code:
function remove_hidden_elements() {
var myElements = $$('.table-row');
myElements.each(function (item, index) {
var vis = item.getStyle('display');
if (vis == 'none') {
item.dispose();
}
});
}
Please can someone point me in the right direction for achieving this within jQuery?
Many thanks in advance.
jQuery and MooTools aren’t really all that far apart; jQuery is more set-oriented and MooTools more element-orientated, but other than that…
The literal jQuery equivalent is:
Basically, swapping
$$()for$()(akajQuery()) and using the raw DOM element that jQuery will pass into its version ofeachto check thestyle.displayproperty, and then usingremove(which will also find and destroy any event handlers or other associated data, provided they were hooked up / associated via jQuery).Somewhat more idiomatic jQuery might be:
Or even eliminating the variable:
jQuery’s
:visibleselector handles several cases other than the literalstyle.display == 'none', and:notinverts it. (Or rather more directly, use:hiddenas 3nigma points out — I must be tired.) But if you specifically want to handle just that case ofstyle.display == 'none'(and there’s nothing wrong with that, it can be more efficient), use the first example above (with or without themyElementsvariable).