Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 510
Akam Avatar asked Jan 23 '16 14:01

Akam


3 Answers

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>
like image 108
Ibrahim Khan Avatar answered Oct 25 '22 19:10

Ibrahim Khan


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!!!)
like image 23
A. Wolff Avatar answered Oct 25 '22 19:10

A. Wolff


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>
like image 27
Zakaria Acharki Avatar answered Oct 25 '22 18:10

Zakaria Acharki