jQuery: how to do something only if element exist? -
i'm new jquery , think question answered many times. can't suggest how find it. while writing jquery code, write constructions selector repeated:
if( $( ".someclass .someclass #someid" ).filter( ":visible" ) ) { $( ".someclass .someclass #someid" ).filter( ":visible" ).click(); // must executed if element found. return; } // must executed if first element not found if( $( ".someotherclass #someotherid" ).filter( ":hidden" ) ) { $( ".someotherclass #someotherid" ).filter( ":hidden" ).show(); return; }
as can see, selector text repeated. way re-use result of last matched selector inside "if()"? example, like:
if( $( ".someclass .someclass #someid" ).filter( ":visible" ) ) { $( ":last-result" ).click(); return; } if( $( ".someotherclass #someotherid" ).filter( ":hidden" ) ) { $( ":last-result" ).show(); return; }
simply don't test, won't make error if there no matching element :
$( ".someclass .someclass #someid:visible").click();
this being said, can have 1 element given id, should use
$("#someid:visible").click();
now, supposing want test, may use
$("#someid:visible").each(function(){ var $element = $(this); // use $element });
another basic solution cache element before test :
var $element = $("#someid"); if ($element.is(":visible")) { // use $element }
Comments
Post a Comment