如何获取元素后的文本节点?

时间:2012-10-22 18:56:22

标签: javascript jquery jquery-selectors textnode

使用jQuery。 我有以下html:

<input type="checkbox" name='something' value='v1' /> All the world <br />

我如何获得文字。我应该使用什么选择器? (我需要“全世界”)

我也无法触及HTML ...

4 个答案:

答案 0 :(得分:52)

尝试使用DOM函数.nextSibling选择下一个节点(包括文本节点)并使用nodeValue获取文本All the world

$(':checkbox')[0].nextSibling.nodeValue

答案 1 :(得分:5)

只需使用普通的JavaScript nextSibling,但你必须“退出”jQuery才能使用该方法(因此[0]):

var text = $('input:checkbox[name="something"]')[0].nextSibling.nodeValue;

JS Fiddle demo

我终于意识到我的其他建议出了什么问题,已经修复了:

var text = $('input:checkbox[name="something"]').parent().contents().filter(
    function(){
        return this.nodeType === 3 && this.nodeValue.trim() !== '';
    }).first().text();

JS Fiddle demo

并确保您只是在textNodes之前从获取br(虽然坦率地说这变得过于复杂,但第一个建议很有效更容易,我怀疑可靠):

var text = $('input:checkbox[name="something"]').parent().contents().filter(
    function(){
        return this.nodeType === 3 && this.nodeValue.trim() !== '' && $(this).prevAll('br').length === 0;
    }).text();

JS Fiddle demo

答案 2 :(得分:3)

如果您在标记中添加label(建议使用),则可以这样做:

HTML

<input type="checkbox" id="something" name="something" value="v1" /><label for="something">All the world</label> <br />

JS

var text = $( '#something ~ label:first' ).text();

答案 3 :(得分:0)

在一个示例中,您遇到一个古老的问题,将文本包装在标签中

$('input[type="checkbox"]')
  .each(function(index, el) {
    var textNode = $(el.nextSibling);
    if (textNode[0].nodeType == Node.TEXT_NODE) {
      let checkwrap = $(el).wrap('<label class="found"></label>').closest('.found');
      textNode.appendTo(checkwrap);
    }
  });
.found {
  border: solid cyan 1px;
  color: blue;
  padding: 0.5em;
  display: inline-block;
  margin: 0.3em;
}

label.found {
  color: lime;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<span>in a span</span>
<input type="checkbox" name='something' value='v1' /> All the world <br />
<input type="checkbox" name='something2' value='v2' /> All the world 2 <span>in a span</span><br />
<input type="checkbox" name='something3' value='v3' /> All the world 3 <span>in a span</span>
<input type="checkbox" name='something4' value='v4' /> All the world 4<span>in a span also</span>

有一个包裹在标签中的标签,哦,等等,这是一个答案,只需要按类型隔离nextSibling