14

In making a US map that displays store locations using this map plug in I've got it mostly nailed down but want a better way to perform one funciton. I have a list of stores below the map and want to group all stores in the same state and display the store names in a sidebar when you hover over the state. I have the hover and displaying of data working but want to improve. Instead of just writing a function for each state and explicitly stating what to display, I would like to get the first p.cn from each div that has the same class.

<div class="texas">
    <p class="cn">Store 1</p>
</div>

<div class="texas">
    <p class="cn">Store 2</p>
</div>

mouseoverState: {
    var texas = $('.texas > p.cn').text();
    $('#mysidebarID').html(texas);
}

This is only displaying the first store "store 1" I cannot get it to grab every p.cn from each div.texas and display them with a <br> after each one.

How do I get the html from every element with the same class and combine it into a string with each node separated by a <br>?

thank you - let me know if I need to clarify anything.

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
Dirty Bird Design
  • 5,333
  • 13
  • 64
  • 121
  • http://stackoverflow.com/questions/4735342/jquery-to-loop-through-elements-with-the-same-class – i-- Aug 20 '12 at 01:39

1 Answers1

33

You can use the each() method, try the following:

var str = "";

$('.texas > p.cn').each(function(){
  str += $(this).text() + "<br>";
})

$('#mysidebarID').html(str);
Ram
  • 143,282
  • 16
  • 168
  • 197
  • 4
    man that's the good stuff. Very much appreciated, and a lesson learned! – Dirty Bird Design Aug 20 '12 at 01:37
  • 1
    Long time Brother +1 `:)` old name is back Ramison `:P` – Tats_innit Aug 20 '12 at 01:40
  • 1
    @Tats_innit _Raminson_? Who is he? `:P` Hey Bro, yes, long time `:)` – Ram Aug 20 '12 at 01:46
  • 1
    @undefined ha ha yea bruv, loooong time for me, good to see you! `:)` – Tats_innit Aug 20 '12 at 01:47
  • How would you concantenate(sp?) the $('.texas > p.cn') with another p, p.tel without having to create another var and function and join that in the '#mysidebarID'.html(str newvar)? – Dirty Bird Design Aug 20 '12 at 01:52
  • 1
    @DirtyBirdDesign Do you mean without the each loop? You can use the `eq` method for selecting the elements separately, then you can concatenate the strings by using `+=` operator or `+`. – Ram Aug 20 '12 at 01:55
  • @undefined - yeah i might want to build the listing with the phone number (p.tel) under the name (p.cn) Intellectually I almost understand what you stated above, in practice, Im not close. – Dirty Bird Design Aug 20 '12 at 01:59
  • @DirtyBirdDesign You can post another question for this. – Ram Aug 20 '12 at 02:16