8

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?

3 Answers 3

16
jQuery("#storeList li").each(function() {
  var n = jQuery(this).find(".address").text(); // <- This works
  alert(n);
});
Sign up to request clarification or add additional context in comments.

4 Comments

better to prefix the selectors with the node name also - jQuery(this).find("div.address")
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.
Yes, node selectors will select an element faster. Conversely with CSS if you make your selector too specific, it slows down the selector process.
I spent about an hour trying to build a similar query to no avail. It kept giving me objects and messages about "v" is not a function (I was using the standard "i" and "v" notation as is taught with JavaScript). I finally found this post. Eureka! My issue was that I was doing $('this') instead of $(this) (I didn't need quotes). Thanks so much!
4
$('#storeList li').each(function() 
{
  var n = $(this).find('div.address').html(); 
  alert(n);
});

Comments

-1
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.

3 Comments

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.
Is that cynical? I'm just trying to help... I didn't down vote it, by the way, though it's understandable.
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.