KaiserCoaster
KaiserCoaster

Reputation: 83

How to get text from an element with other children using jQuery

I have something similar to the following:

<div>
     Hello World
     <div>Something Else</div>
</div>

I want to use javascript/jQuery to get just the 'Hello World' text. I could just wrap it in a span and select that, but I now want to know how to do this.

I thought simply using $('div').text() would work, but it gives me "Hello WorldSomething Else".

Thanks, Matt

Upvotes: 4

Views: 176

Answers (5)

Ram
Ram

Reputation: 144739

Try this:

var div = document.getElementsByTagName('div')[0].firstChild;
var text = div.textContent ? div.textContent.trim() : div.innerText;

Fiddle

Please note that IE8 and earlier versions don't support the trim function, if you are using jQuery you can use the jQuery $.trim() utility function which is cross-browser. $.trim(text)

Upvotes: 2

RichardTowers
RichardTowers

Reputation: 4762

Sorry if this is too similar to @minitech's answer:

var text = $('div:first')
    .contents()
    .filter(function() {
        return (this.nodeType === 3);
    }).text();

alert(text);​

You can use a combination of contents() (gets the contents of the selected elements) and filter() to reduce the matched set to text only (nodetype === 3 means 'Text').

jsFiddle

Of course, you could use first() instead if you were confident about how your html was going to look:

var text = $('div:first')
    .contents()
    .first()
    .text();

jsFiddle

Upvotes: 1

adeneo
adeneo

Reputation: 318352

Clone the element (the first div), remove all children and get the text, optionally remove whitespace with $.trim() :

var elm = $('div:first').clone();
var text = $.trim(elm.children().remove().end().text());

FIDDLE

Upvotes: 0

Mitya
Mitya

Reputation: 34608

text(), as you've discovered, gets the text not only of the targeted node(s) but also of any child/descendant nodes.

Even if this wasn't the case, your code in its current form would still return a concatenation of both pieces of text because your selector targets simply div, so jQuery will go find all divs and get their text, as one chunk of text.

You can get an element's immediate text only with something like this, though there are other ways.

//make a mini plugin for getting the immediate text of an element
$.fn.extend({
    immediateText: function() {
        return this.clone().find("*").remove().end().text();
    }
});

//use the plugin
var immediateText = $('#some_element').immediateText();

Upvotes: 1

Ry-
Ry-

Reputation: 225281

Use .contents:

yourDiv.contents().filter(function() {
    return this.nodeType === 3;
}).map(function() {
    return this.nodeValue;
}).get().join('');

Alternatively, sans jQuery:

var i, c, result = '';

for(i = 0; c = yourDiv.childNodes[i]; i++) {
    if(c.nodeType === 3) {
        result += c.nodeValue;
    }
}

Upvotes: 0

Related Questions