1

How would I receive only the direct text, not including children and children's text?

For example in this case I would like to receive "Lorem":

<div>
  Lorem
  <div>
    Ipsum
  </div>
</div>

4 Answers4

1

Once you get a reference to the div, from your jQuery I'm assuming it has the class title

var div = document.getElementsByClassName('title')[0]; //get the reference to the parent div
var name = div.firstChild.nodeValue;

alert(name)
<div class="title">
  hi
  <div>
    asd
  </div>
</div>

If you want to complicate it

var div = document.getElementsByClassName('title')[0]; //get the reference to the parent div
var array = [].map.call(div.childNodes, function(child) {
  return child.nodeType == 3 && child.nodeValue.trim() ? child.nodeValue.trim() : undefined;
})
var name = array.join();

alert(name)
<div class="title">
  hi
  <div>
    asd
  </div>
  this also
</div>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Arun, What does the [0] in the first line denote? – MarsOne Oct 14 '14 at 09:32
  • @MarsOne `getElementsByClassName` returns an array like `NodeList` so we need to access the first element from that using index – Arun P Johny Oct 14 '14 at 09:33
  • Of course this code only gets the first text node's text... Based on the jQuery version I suspect they may want all text (excluding all children), but the question is quite vague. – iCollect.it Ltd Oct 14 '14 at 09:35
1

You can write this way:

alert($(".title").clone().children().remove().end().text())

Snippet:

$(function(){
  alert($(".title").clone().children().remove().end().text());
});
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<div class="title">
  hi
  <div>
    asd
  </div>
</div>

or write your own function as shown in this SO post in the jquery and can reuse it wherever needed.

jQuery.fn.justtext = function() {

    return $(this).clone()
            .children()
            .remove()
            .end()
            .text();

};

alert($('#mydiv').justtext());​
Community
  • 1
  • 1
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
0

Below code works...

$('div').filter(function(){
    console.log( $.trim($(this).clone().context.firstChild.data) );
});
Divakar Gujjala
  • 803
  • 8
  • 24
-1

If you want to get hi only try this :

var element = $("div:first").text();