tags:

views:

397

answers:

3

I need to get the div containing the street address within the list. The div has a class called address ( div class="address" )

I cannot use jQuery("#storeList li .address"), because there are other elements I need to acces as well.

I have the following code:

jQuery("#storeList li").each(function() {
  var n = jQuery(this.address).text(); // <- This does not work
  alert(n);
});

How do I access each DIV element of type Address?

+4  A: 
jQuery("#storeList li").each(function() {
  var n = jQuery(this).find(".address").text(); // <- This works
  alert(n);
});
Scharrels
Super. Thanks! :)
Steven
better to prefix the selectors with the node name also - jQuery(this).find("div.address")
redsquare
It depends. If you prefix the selector with the node name, you cannot change the structure of the elements (e.g. replace a div by a span) without having to change the javascript code. On the other hand, jQuery might select the element faster if you use node selectors.
Scharrels
Yes, node selectors will select an element faster. Conversely with CSS if you make your selector too specific, it slows down the selector process.
Will Morgan
A: 
jQuery("#storeList li:has(.address) .address").each(function() {
    alert(this.innerHTML);
});

An alternative that avoids using a second query. As a jQuery newbie I don't know what the tradeoffs really are though.

Bill Bell
That's nice if you only care about address, but not if you have more fields, or what to handle li without addresses. Also, you don't need `li:has(.address) .address`, it's the same but slower than `li .address` - you're selecting the `.address`, so you know it's there.
Kobi
Very encouraging, Kobi.
Bill Bell
Is that cynical? I'm just trying to help... I didn't down vote it, by the way, though it's understandable.
Kobi
I _was_ being sarcastic and I did assume you down-voted it. Apologies. I really can't see the point of that. Why would anyone offer a different possibility?
Bill Bell
+1  A: 
$('#storeList li').each(function() 
{
  var n = $(this).find('div.address').html(); 
  alert(n);
});
Raghav Khunger