Here is a piece of html for a radio button that is currently selected:
<label>
<input type="radio" name="reason" value="1" data-promo="1">
"some text here bla bla"
</label>
With a line of JS I found over here I am able to grab the input element but not the text:
document.querySelector('input[name="reason"]:checked');
Returns:
<input type="radio" name="reason" value="1" data-promo="1">
How would I grab the text that follows this element "some text here bla bla"?
If you don't know the position of the text in advance, then the simpliest option is to access the textContent
property of the parent label
element:
document.querySelector('input[name="reason"]:checked').parentElement.textContent;
Of course, this assumes that is the only text node in the label
element.
Alternatively, if the text always appears after the input
element, then you could just access the textContent
property of the next sibling:
document.querySelector('input[name="reason"]:checked').nextSibling.textContent;
The text node is the next sibling of the checkbox so
function test() {
var checkbox = document.querySelector('input[name="reason"]:checked');
if (checkbox) {
var text = checkbox.nextSibling.textContent;
alert(text);
}
}
<label>
<input type="radio" name="reason" value="1" data-promo="1">text 1
</label>
<label>
<input type="radio" name="reason" value="2" data-promo="2">text 2
</label>
<label>
<input type="radio" name="reason" value="3" data-promo="3">text 3
</label>
<label>
<input type="radio" name="reason" value="4" data-promo="4">text 4
</label>
<button onclick="test()">Test</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With