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