2011-10-18 33 views
2

當父元素也是DIV時,如何獲取子DIV元素的內容。我想爲每個孩子的內容添加新行。這是我的HTML。獲取子div的內容jquery

<div id="Messages"> 
    <div class="MessageNew">This is test message </div><br> 
    <div class="Message">Thank you ... </div><br> 
    <div class="Message">Third test message. </div><br> 
</div> 

這是我曾嘗試

var msgs = $("#Messages").text(); 

我得到這個輸出

This is test message Thank you ... Third test message. 

這就是我想要

This is test message 
Thank you ... 
Third test message. 

回答

9

試試這個:

$('#Messages div').each(function(index) { 
    alert($(this).text()); 
}); 
0

不考慮你的<br>元素,你可以這樣做:

var msgs = ""; 
$("#Messages div").each(function() { 
    msgs += $(this).text() + "\n"; 
}); 
alert(msgs); 

http://jsfiddle.net/Xeon06/LWTrt/

這只是經過內#Messages所有div元素,並將它們添加到新的字符串行分隔符。

0

你需要在它們之間放置一個換行符。

你可以做類似

var msg = ""; 
$("Messages div").each(function(d) { 
    msg += "\r\n" + $(this).text(); 
} 
msg = msg.substring(2); //to remove the first "\r\n" 

或者,您可以添加一個新行前檢查長度,只有做到這一點,如果已經有文字。

當然,如果你想在其他地方(就像另一個HTML元素內)顯示該文本,應更換\r\n<br />