How to get text node after element?

淺唱寂寞╮ 提交于 2019-11-26 17:47:47

问题


Using jQuery. I have the following html:

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

How would I get ONLY the text. what selector should I use? (I need the "All the world")

I also can not touch the HTML...


回答1:


Try using the DOM function .nextSibling to pick the next node (including the text nodes) and use nodeValue to get the text All the world

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



回答2:


Just use the plain-JavaScript nextSibling, though you have to 'drop out of' jQuery to use that method (hence the [0]):

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

JS Fiddle demo.

And I finally realised what was wrong with my other suggestion, which has been fixed:

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

JS Fiddle demo.

And to make sure that you're only getting the textNodes from before the br (though frankly this is becoming overly-complex, and the first suggestion works far more easily and, I suspect reliably):

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.




回答3:


If you added a label to your markup (which is recommended), you could do it this way:

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();



回答4:


Just to toss in a example to a way old question, wrap text in a label

$('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>

there, wrapped in a label, oh wait, that is an answer, just have to get the nextSibling isolated by type



来源:https://stackoverflow.com/questions/13017894/how-to-get-text-node-after-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!