Akam
Akam

Reputation: 1052

JQuery get only text of element not text of childs

I have a big table which I need to convert some text to another Unicode entities, but some cells contains another html elements for example:

<td>some text <span>another text</span></td>

I want to get some text only because I can get the first child span by:

children().eq(0)

I tried

$(this).text() //but gets all text inside the cell

Upvotes: 6

Views: 5323

Answers (3)

A. Wolff
A. Wolff

Reputation: 74420

In jQuery, you need to filter out its content to get textnode text:

$(this).contents().filter(function(){
    return this.nodeType === 3;
}).text(); // >> "some text "

And this is where jQuery becomes funny:

$(this).contents().not(':not(:not(*))').text();  // >> "some text "

While:

$(this).contents().not('*').text(); // >> "" (empty string!!!)

Upvotes: 3

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Using Jquery you could clone the element and remove his childrens then get text :

$('td').clone().children().remove().end().text();

Hope this helps.


alert( $('p').clone().children().remove().end().text() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>some text <span>another text</span></p>

Upvotes: 2

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

You can get some text like following.

this.childNodes[0].nodeValue

Example

$('td').click(function () {
    alert(this.childNodes[0].nodeValue)
}) 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr>
        <td>some text <span>another text</span></td>
    </tr>
</table>

Upvotes: 6

Related Questions