使用jquery获取span元素后面的文本

时间:2022-12-15 20:30:02

I have this html code

我有这个HTML代码

<div id="mydiv">
    <div>
        <span>Text inside span</span>
        Text next to span
    </div>
    <div>
        Contents inside the 2nd div element...
    </div>
</div>

I wanted to get the "Text next to span". I tried this code JQuery code

我想得到“文本旁边的跨度”。我试过这段代码JQuery代码

var a = $('#mydiv div').first().find('span').parent().text();
alert(a);

The output of the jquery code above is this:

上面的jquery代码的输出是这样的:

Text inside span
Text next to span

What should be the right thing to do to just get only the "Text next to span"?

如果只获得“文本旁边的跨越”,应该做什么才是正确的做法?

3 个解决方案

#1


43  

var a = $('#mydiv div').first().contents().filter(function() {
    return this.nodeType == 3;
}).text();

This gets the contents of the selected div, and filters the matched set, returning only elements with nodeType == 3, which are text nodes.

这将获取所选div的内容,并过滤匹配的集合,仅返回nodeType == 3的元素,这些元素是文本节点。

#2


7  

Use this code:

使用此代码:

 $('#myDiv')
  .contents()
  .filter(function() {
    return this.nodeType == Node.TEXT_NODE;
  }).text();

#3


6  

I got it by this:

我明白了:

$('#mydiv div').first().contents().eq(1).text();

#1


43  

var a = $('#mydiv div').first().contents().filter(function() {
    return this.nodeType == 3;
}).text();

This gets the contents of the selected div, and filters the matched set, returning only elements with nodeType == 3, which are text nodes.

这将获取所选div的内容,并过滤匹配的集合,仅返回nodeType == 3的元素,这些元素是文本节点。

#2


7  

Use this code:

使用此代码:

 $('#myDiv')
  .contents()
  .filter(function() {
    return this.nodeType == Node.TEXT_NODE;
  }).text();

#3


6  

I got it by this:

我明白了:

$('#mydiv div').first().contents().eq(1).text();