2016-11-29 33 views
2

如何讓所有的text<br/>tag如何讓後<br>標籤文本

我的HTML是這樣

<i class="loc">cherry<br>From Shimla</i> 
<i class="loc">Apple<br>from kashmir</i> 
<i class="loc">banana<br>From bihar</i> 

預期輸出:["From Shimla","from kashmir","From bihar"];

我試圖像什麼這

var arr = []; 
 

 
$('.loc').each(function(){ 
 
    arr.push($(this).text()); 
 
}); 
 
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> 
 
<i class="loc">cherry<br>From Shimla</i> 
 
<i class="loc">Apple<br>from kashmir</i> 
 
<i class="loc">banana<br>From bihar</i>

回答

3

您可以定位br元素,並使用.get(index)來獲取潛在的DOM元素,採用nextSibling爲目標的文本節點。然後nodeValue屬性可以用來獲取文本。

var arr = []; 
 
$('.loc').each(function() { 
 
    arr.push($(this).find('br').get(0).nextSibling.nodeValue); 
 
}); 
 
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> 
 
<i class="loc">cherry<br>From Shimla</i> 
 
<i class="loc">Apple<br>from kashmir</i> 
 
<i class="loc">banana<br>From bihar</i>

可以進一步提高你的代碼爲

var arr = $('.loc').map(function() { 
 
    return $(this).find('br').get(0).nextSibling.nodeValue; 
 
}).get(); 
 
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> 
 
<i class="loc">cherry<br>From Shimla</i> 
 
<i class="loc">Apple<br>from kashmir</i> 
 
<i class="loc">banana<br>From bihar</i>

+0

非常感謝工作完全 –

1
var arr = []; 

$('.loc').each(function(){ 
    arr.push($(this).html().split('<br>')[1]); 
}); 
console.log(arr); 

您可以使用HTML(),把它分解,並使用第二個值來自陣列。

var arr = []; 
 

 
$('.loc').each(function(){ 
 
    arr.push($(this).html().split('<br>')[1]); 
 
}); 
 
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<i class="loc">cherry<br>From Shimla</i> 
 
<i class="loc">Apple<br>from kashmir</i> 
 
<i class="loc">banana<br>From bihar</i>

1
var arr = []; 

    $('.loc').each(function(){ 
     arr.push($(this).children('br').get(0).nextSibling); 
    }); 
console.log(arr); 
+0

雖然此代碼段可以解決的問題,[包括一個解釋](http://meta.stackexchange.com/questions/114762/explaining - 完全基於代碼的答案)確實有助於提高發布的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 – secelite

相關問題