Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get text inside of container that is not part of children

Tags:

jquery

Let's have html code like this:

<div id="d1"><span>1.</span>Hallo <span>Kitty, </span><div>How are you?</div></div>

It is just example, there may be different children elements inside.

How can I get text inside of d1 container that is not part of children elements?

For the example above it shold be just "Hallo "

like image 316
Ωmega Avatar asked Dec 12 '22 21:12

Ωmega


2 Answers

this will work for you

$('#d1')
  .contents()
  .filter(function() {
    return this.nodeType == Node.TEXT_NODE;
}).text()

or you can use this as suggested below for old browser support also

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

Demo

like image 199
rahul Avatar answered May 25 '23 05:05

rahul


http://jsfiddle.net/SGZW4/

var text = $("#d1").contents().filter( function() {
    return this.nodeType === 3;
}).text();
like image 43
Esailija Avatar answered May 25 '23 04:05

Esailija