0

How do I select the "some text" only with jQuery?

<p class="a">some text<a href="">some other text</a></p>

Here above is the code.

I guess $('p.a').text() is not working correctly.

console.log($('p.a').text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="a">some text<a href="">some other text</a></p>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
darkrose1977
  • 197
  • 1
  • 2
  • 11

4 Answers4

0
$('p.a').contents().filter(function () { return this.nodeType === 1; });
Jaspreet Jolly
  • 1,235
  • 11
  • 26
  • 1
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation would greatly improve its long-term value](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) by showing why this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made. – common sense Feb 09 '19 at 13:26
0

You can have your own function to ignore the child elements

$.fn.ignoreChildren = function(child){
    return this.clone().find(child||">*").remove().end();
};

alert($(".a").ignoreChildren('a').text()); // Alerts 'some text'
Prasann
  • 1,263
  • 2
  • 11
  • 18
0

Try this:

console.log($('p.a').contents().not($('p.a').children()).text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="a">some text<a href="">some other text</a></p>
Partho63
  • 3,117
  • 2
  • 21
  • 39
0

Use the clone method to get only main node and remove all other child node from that. Then get your content. Check below code:

console.log($("p.a").clone().children().remove().end().text());

I have checked this and it is working fine. Hope it helps you.

Rohit Mittal
  • 2,064
  • 2
  • 8
  • 18