1

I am try to get the specific text using jquery, Here is my code,

<div class='sometext'>
sometext
<span class="innerspan">span_text</span>

</div> 

From the above html I need to get the sometext using jquery like this,

$('.sometext').text() 

But I received the output sometextspan_text.

How to get the sometext only ?

codeimplementer
  • 3,303
  • 2
  • 14
  • 16

3 Answers3

1

Just get the first node you can find, which is a text node in your case:

$('.sometext').contents().get(0);

This is a bit fragile, so another approach is by first getting all child text nodes:

$('.sometext').contents().filter(function() {
    return this.nodeType == 3;
});

And then take the first of that:

$('.sometext').contents().filter(function() {
    return this.nodeType == 3;
})[0];
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
-1

I think you shoul organize every text nodes inside ".sometext" div, for example inside a div or p tag like the following:

<div class='sometext'><p>sometext</p><span class="innerspan">span_text</span></div>

Then you'll be able to access ".sometext" div's children with the JQuery Children function.

$(".sometext").children()[0]

The index depends of the position of the element inside the di, I suggest you read the docs of the function. Hope this helps you my friend!

MRodriguez08
  • 189
  • 1
  • 7
-1

Please see the code below.

$('.sometext')
        .contents()
        .filter(function(){
             return this.nodeType == 1; 
        }).hide();
codeimplementer
  • 3,303
  • 2
  • 14
  • 16