This is what I have in html file
<label><input type="checkbox" id="abc-news-au" /> ABC News (AU)</label><br /> <label><input type="checkbox" id="ars-technica" /> Ars Technica</label><br /> <label><input type="checkbox" id="associated-press" /> Associated Press</label><br />
I want to get the text between labels Ex. ABC NEWs (AU)
I use the following code but didnt work *(v is the id of the element)
console.log("get text: "+ $("#"+v).text()) //(empty)
console.log("get text: "+ $("#"+v).html()) //undefined
The only code that shows something is
console.log("get text: "+ v) //abc-news-au
which is obviously the id of the element... How do I get the text of the element?
You can use $("#"+v).parent().text()
to get what you want. This is because the text is inside <label>
node, not <input>
node.
Example: https://jsfiddle.net/epL3tkza/
<input />
does not have any html()
or text()
. It's a self closing tag. You want to get the .text()
of it's wrapping <label>
.
Using jQuery
:
$('body').on('click','input', function(e){ console.log($(e.target).closest('label').text()); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label><input type="checkbox" id="abc-news-au" /> ABC News (AU)</label><br /> <label><input type="checkbox" id="ars-technica" /> Ars Technica</label><br /> <label><input type="checkbox" id="associated-press" /> Associated Press</label><br />
I want to get the text between labels Ex. ABC NEWs (AU)
you could use the DOM node nextSibling
property, example:
<!DOCTYPE html> <html> <body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label><input type="checkbox" id="abc-news-au" /> ABC News (AU)</label><br /> <label><input type="checkbox" id="ars-technica" /> Ars Technica</label><br /> <label><input type="checkbox" id="associated-press" /> Associated Press</label><br /> <script> $('input[type=checkbox]').click(function (e) { if($(this).is(':checked')) { var data = this.nextSibling.nodeValue; console.log(data); } }); </script> </body> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.