How to get text node after element?

后端 未结 4 990
太阳男子
太阳男子 2020-11-29 09:23

Using jQuery. I have the following html:

 All the world 

How w

相关标签:
4条回答
  • 2020-11-29 09:25

    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.

    0 讨论(0)
  • 2020-11-29 09:27

    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();
    
    0 讨论(0)
  • 2020-11-29 09:37

    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
    
    0 讨论(0)
  • 2020-11-29 09:46

    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

    0 讨论(0)
提交回复
热议问题