JQuery is retrieving the options text along with the label text

0

While working on something I stumbled in the following situation. Here is the code with the "problem":

var oi = $("label").text();
$("div").html(oi);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Hello
  <select>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  </select>
</label>

<div></div>

I wanted to pull only the text of the label but the texts within options are coming together. Can you work around this with JQuery or pure Javascript?

PS. I know it's possible to 'link' a label with an element using 'for' but I wanted to avoid this way, I'm working on an extensive form and creating unique id's just for the labels is pretty exhaustive.

    
asked by anonymous 24.05.2017 / 23:04

1 answer

0

var oi = $("label").clone().children().remove().end().text();
$("div").html(oi);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Hello
  <select>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  </select>
</label>

<div></div>
    
24.05.2017 / 23:29