Get the text from all elements with the same class

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.


您可以使用each()方法,请尝试以下操作:

var str = "";

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

$('#mysidebarID').html(str);
链接地址: http://www.djcxy.com/p/83510.html

上一篇: 将值从DIV元素传递到输入

下一篇: 从具有相同类的所有元素中获取文本