2

I'm new to jQuery and i think this question was answered many times. But i can't suggest how to find it. While writing jQuery code, i often write constructions where selector is repeated:

if( $( ".someclass .someclass #someid" ).filter( ":visible" ) ) { $( ".someclass .someclass #someid" ).filter( ":visible" ).click(); // This must be executed only if element was found. return; } // This must be executed only if first element not found if( $( ".someotherclass #someotherid" ).filter( ":hidden" ) ) { $( ".someotherclass #someotherid" ).filter( ":hidden" ).show(); return; } 

As you can see, selector text is repeated. Is it any way to re-use result of last matched selector inside "if()"? For example, something like:

if( $( ".someclass .someclass #someid" ).filter( ":visible" ) ) { $( ":last-result" ).click(); return; } if( $( ".someotherclass #someotherid" ).filter( ":hidden" ) ) { $( ":last-result" ).show(); return; } 
1

2 Answers 2

3

Simply don't test, this won't make any error if there is no matching element :

$( ".someclass .someclass #someid:visible").click(); 

This being said, as you can only have one element with a given id, you probably should use

$("#someid:visible").click(); 

Now, supposing you really want to do a test, then you may use

$("#someid:visible").each(function(){ var $element = $(this); // use $element }); 

Another basic solution is to cache your element before the test :

 var $element = $("#someid"); if ($element.is(":visible")) { // use $element } 
Sign up to request clarification or add additional context in comments.

5 Comments

This was my first fought :). Unfortunately, in many cases i need to click/show/hide and do something else. For example, in my code sample - return from method. Or write something to log. Or whatever.
It's not clear what you want but you can use this in most cases if you use each.
@Kevin Sorry, i can't understand. If i add it to next line after "click" - it will execute if element is visible and if it's not visible. And it's common to do logic like "if something is visible - hide and return. Than check if something else if not visible, if so - show and return. Finally, check some element has text. If so, clear and return."
Yes, something like temporary variable. Does jQuery provides some shortcut to it like "last-match"?
No, that wouldn't really make sense. If you need to use a value more than once, declare a variable. See the various solutions in my answer.
1

If you really want to do something only if element exist

$('element').length == 0; // no element found 

By using the .length property we can test whether an element exists, or whether it has been found in the page.

Read more

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.