Heejoo Jang Heejoo Jang - 6 months ago 12
Javascript Question

get textNode with division from div tag

<div class="list" data-id="1">One</div>
<div class="list" data-id="2">Two</div>
<div class="list" data-id="3">Three</div>
<div class="list" data-id="4">Four</div>





var text = $(".list").contents().filter(function() {
return this.nodeType == 3; }).text()
alert(text);


Now, I get alert "OneTwoThreeFour"

But, I want to get "One|Two|Three|Four" like this ....using "|" division

Please help me.......

Answer

Use .join() after jQuery.map()

The join() method joins all elements of an array into a string.

jQuery.map() translate all items in an array or object to new array of items.

var text = $(".list").map(function() {
  return this.textContent;
}).get();

alert(text.join('|'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="list" data-id="1">One</div>
<div class="list" data-id="2">Two</div>
<div class="list" data-id="3">Three</div>
<div class="list" data-id="4">Four</div>

Or using your approach

var text = $(".list").contents().filter(function() {
  return this.nodeType == 3;
}).get();
text = text.map(function(t) { //.map as text is a collection of `TextNode` objects
  return t.textContent;
});
alert(text.join('|'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="list" data-id="1">One</div>
<div class="list" data-id="2">Two</div>
<div class="list" data-id="3">Three</div>
<div class="list" data-id="4">Four</div>