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
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>
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!!!)
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With