3

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

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Nicki Evans
  • 127
  • 8
  • Possible duplicate of [Get the text after span element using jquery](https://stackoverflow.com/questions/6925088/get-the-text-after-span-element-using-jquery) – Xzandro Dec 27 '18 at 11:21
  • Place `second text` inside the span tag and then try – vinay kumar reddy Dec 27 '18 at 11:22
  • @Xzandro nope, that is slightly different, the solution for the mentioned question is just check for type text, but here if I use that, it returns me both **First text** and **Second text** – Nicki Evans Dec 27 '18 at 11:30
  • @vinaykumarreddy I can't modify `html` code – Nicki Evans Dec 27 '18 at 11:32
  • 1
    `const a = $('div span').contents().eq(2).text();` Well, it's a bit different, yes, but the idea behind it is basically the same. – Xzandro Dec 27 '18 at 11:38

2 Answers2

1

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>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
1

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>
Jitendra G2
  • 1,196
  • 7
  • 14