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

问题描述 投票:30回答:4

使用jQuery。我有以下html:

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

我怎么才能获得文本。我应该使用什么选择器? (我需要“全世界”)

我也无法触摸HTML ...

javascript jquery jquery-selectors textnode
4个回答
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();

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

© www.soinside.com 2019 - 2024. All rights reserved.