Nicki Evans
Nicki Evans

Reputation: 137

Get text, which goes after span element, not including the text that is before the span, using jquery

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

Answers (2)

Jitendra G2
Jitendra G2

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

Zakaria Acharki
Zakaria Acharki

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

Related Questions