我有这个HTML代码:
<div>
<span>
First text
<span class="dot"></span>
Second text
</span>
<span class="other-span">
</span>
</div>
我只需要获得第二个文本。我尝试了以下JQuery代码:
const a = $('div').find('span:nth-child(1)').text();
console.log(a);
上面的jquery代码的输出是这样的:
First text Second text
在具有类点
的 span 元素之后仅获得第二文本的正确做法是什么答案 0 :(得分:1)
您可以获取HTML,然后像这样剥离文本:
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>
答案 1 :(得分:1)
您可以使用nodeType属性。我希望下面的示例会有所帮助,
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>