How to get text node after element?

Related searches

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...

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

ChildNode.after(), HTML string, DOM element, text node, array of elements and text nodes, DOM element(s), text node(s), or jQuery object to insert after each element in the set of The method might or might not have returned a new result depending on the� The ChildNode.after() method inserts a set of Node or DOMString objects in the children list of this ChildNode's parent, just after this ChildNode. DOMString objects are inserted as equivalent Text nodes. Syntax [Throws, Unscopable] void ChildNode.after((Node or DOMString) nodes); Parameters nodes A set of Node or DOMString objects to insert. Exceptions

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.

.after(), DOM element, text node, array of elements and text nodes, HTML string, or jQuery of arguments will largely depend on how you collect the elements in your code. or method that accepts an HTML string — jQuery(), .append(), .after (), etc. 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.

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

.prepend(), HTML elements often consists of both an element node and a text node. To create a Tip: After the Text Node is created, use the element.appendChild() or� The simplest way would probably be to iterate over all the direct children of the node (using ChildNodes) and test the NodeType of each one to see if it's Text or CDATA.Don't forget that there may be multiple text nodes.

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>

HTML DOM createTextNode() Method, To retrieve the text value of an element, you must retrieve the value of the elements' text node. The getElementsByTagName Method. The getElementsByTagName� To add text to the <p> element, you must create a text node first. This code creates a text node: This code creates a text node: var node = document.createTextNode("This is a new paragraph.");

XML DOM - Get Node Values, textContent returns the text content of all elements, while innerText returns the content of all elements, except for <script> and <style> elements. innerText will not return the text of elements that are hidden with CSS (textContent will). Try it » Tip: Sometimes this property can be used instead of the nodeValue property, but remember that this property returns the text of all child nodes as well. Tip: To set or return the HTML content of an element, use the innerHTML property.

Element nodes do not have a text value. The text value of an element node is stored in a child node. This node is called a text node. To retrieve the text value of an element, you must retrieve the value of the elements' text node.

The createTextNode() method creates a Text Node with the specified text. Tip: Use the createElement() method to create an Element Node with the specified name. Tip: After the Text Node is created, use the element.appendChild() or element.insertBefore() method to append it to an element.

Comments
  • stackoverflow.com/questions/6925088/…
  • If you are going to use filter you can very well use .text() on text nodes.. no need [0].nodeValue.. just that jQuery doesn't have a way to select the text node.
  • This does not yield the text.
  • Even though OP is asking for the node, it seems that the text is actually wanted. Just add .data or .nodeValue to the end.
  • @KevinBoucher: it certainly seems to, in Chromium 18/Ubuntu 11.04. What are you testing in? No, you're right. Edited to correct!
  • @KevinBoucher nextSibling is to get the node.. to get the text you need to do nodeValue
  • +1 assuming this is the label (very likely), but I'd use a valid Selectors API selector instead so that querySelectorAll can be utilized. $('#something + label')
  • What's wrong with the next siblings selector? api.jquery.com/next-siblings-selector
  • Nothing at all, but the :first is a proprietary Sizzle selector, so it defaults to Sizzle's JavaScript based selector engine instead of the browser's native one.
  • @KevinBoucher Right, but the point is it isn't a CSS selector, therefore querySelectorAll can't be utilized, meaning the string then has to be parsed.
  • Can't use label, I can't touch the HTML