Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the text from all elements with the same class

Tags:

jquery

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.

like image 902
Dirty Bird Design Avatar asked Aug 20 '12 01:08

Dirty Bird Design


People also ask

How do I select all items with the same name?

Click Home tab Select & Search panel Select Same drop-down Same Name .


1 Answers

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

var str = "";

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

$('#mysidebarID').html(str);
like image 56
undefined Avatar answered Oct 29 '22 16:10

undefined