Dilip G Dilip G - 10 days ago 5
Javascript Question

how to get the text after <br> tag

how to get all the

text
after
<br/>
tag


my html is like this

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


expected output:
["From Shimla","from kashmir","From bihar"];


i'm trying something like this



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>




Answer

You can target the br element and use .get(index) to fetch the underlying DOM element, the use nextSibling to target the text node. Then nodeValue property can be used to get the text.

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>

You can further improve you code as

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>