PurpleVermont PurpleVermont - 1 year ago 64
Javascript Question

Jquery - extracting and modifying text from an element

I have some elements in my document like:

<div class="checkbox-inline"><label><input id="mylabel" value="False" type="checkbox">mytext</label></div>

When I try to get the text using:


I get an error that text() is not defined on that object. My ids are unique, so my object is in the 0: position in
but both of these return an empty string for the text:


How can I get the text
out of these elements? And how can I programmatically modify it?

I realize now that my problem is slightly different than what I thought it was. Please see: Modifying the text of a label that also contains an input (checkbox) for my follow-up question. Thanks!

Answer Source

I'm assuming you're trying to access the text of the label element, in this case "mytext"? The reason this isn't working is because the id is on the input element, whcih doesn't actually contain that text

<input id="mylabel" value="False" type="checkbox">

That's the entirety of your input element.

As others have stated, you can get the value of that element using


Which will give you "False"

However, if you do need the text "mytext" and don't want to change your markup you can use this


Which gets the element with the mylabel id, finds it's parent element (in this case the label element) and then gets the text from that element.

Now that you know that, you might realise that it's easier to just put an id on the label!