Reputation: 137
I have this HTML code :
<div>
<span>
First text
<span class="dot"></span>
Second text
</span>
<span class="other-span">
</span>
</div>
I need to get only Second text. I tried this JQuery code:
const a = $('div').find('span:nth-child(1)').text();
console.log(a);
The output of the jquery code above is this:
First text Second text
What should be the right thing to do to get only Second text after the span element with class dot
Upvotes: 3
Views: 531
Reputation: 1206
You can use nodeType property. I hope below example will help,
const a = $('div').find('span:nth-child(1)').contents().filter(function() {
return this.nodeType == 3;
})[1]
console.log(a.textContent.trim());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span>
First text
<span class="dot"></span> Second text
</span>
<span class="other-span">
</span>
</div>
Upvotes: 1
Reputation: 67505
You could get the HTML then strips the text like :
const a = $('div').find('span:nth-child(1)').html().split('<span class="dot"></span>')[1];
console.log(a.trim());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span>
First text
<span class="dot"></span> Second text
</span>
<span class="other-span">
</span>
</div>
Upvotes: 1