anon
anon

Reputation:

Get HTML element text without children

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>

Upvotes: 1

Views: 2770

Answers (4)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

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());​

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

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>

Upvotes: 1

Divakar Gujjala
Divakar Gujjala

Reputation: 803

Below code works...

$('div').filter(function(){
    console.log( $.trim($(this).clone().context.firstChild.data) );
});

Upvotes: 0

Syed Muhammad Zeeshan
Syed Muhammad Zeeshan

Reputation: 1045

If you want to get hi only try this :

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

Upvotes: -1

Related Questions