0

Given a this HTML:

<div class="checkbox">
  <label>
    <input id="data_point_occupation" value="occupation" type="checkbox">
    Occupation
  </label>
</div>

I want to get the text content of the label ("Occupation"), but not anything else. Since I'm already using jQuery on the page, I decided to try getting it with jQuery. So I tried the below:

var label = $("#data_point_occupation").parent("label").contents().get(0).nodeValue
console.log(label) // outputs what looks like just white space
console.log(label.length) // outputs 25 

I tried a few other variations in this question, but all of them had similar results.

How can I get the text of this label?

Related but didn't answer my question: jQuery - select the associated label element of a input field

Scribblemacher
  • 1,518
  • 1
  • 16
  • 31

2 Answers2

1

I assume this is what you are looking for:

var label = $("#data_point_occupation").parent("label");
console.log(label.text().trim())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox">
  <label>
    <input id="data_point_occupation" value="occupation" type="checkbox">
    Occupation
  </label>
</div>

This will get the text of the element and trim any whitespace.

Hunter Mitchell
  • 7,063
  • 18
  • 69
  • 116
0

You can use .text() property Here is code

$(document).ready(function(){
  alert($("label").text());
});

Example on http://jsbin.com/dukokucuku/edit?html,js,output

Nil
  • 1,209
  • 9
  • 20