Juw
Juw

Reputation: 2089

Jquery respond to find() fail?

I found this code that let´s me traverse through some xml elements:

$(somexml).find('company[id="'+id+'"] customers customer').each(function()
{
     var $tmp = $(this);
     alert($tmp.attr('customerid'));
});

seems to work pretty good. But since i´m novice at Javascript/Jquery i have some questions:

  1. How can i respond to when the find() failed...no matches?

  2. Why the '$' before tmp? Why not just var tmp = $(this);

Upvotes: 0

Views: 2209

Answers (2)

georg
georg

Reputation: 214959

1: each returns the object it's been called on, that is $(x).each returns $(x). So, assign the result of each to a variable and check its length:

var obj = $(somexml).find(whatever).each(function() {
    ...
});
if(!obj.length)
     nothing has been found...

2: $tmp instead of just tmp is a "hungarian" convention to denote jQuery objects. You are not required to use it.

Upvotes: 3

Adil
Adil

Reputation: 148110

How can i respond to when the find() failed...no matches?

Assign the result to some variable

result = $(somexml).find('company[id="'+id+'"] customers customer');

if(result.length > 0)
{
   result.each(function()
   {
       var $tmp = $(this);
       alert($tmp.attr('customerid'));
   });    
}    
else
{
   alert("No results");
}

Why the '$' before tmp? Why not just var tmp = $(this);

You do not need to use $ before tmp. using $ 

var tmp = $(this); 

Upvotes: 1

Related Questions