Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

closest() not returning the closest label to my input

I need to select the label which is above my input and get its text.

Sometimes it is like that :

<div id="q1">
    <label class="question_label">Label q1</label>
    <input type ="text">
</div>

Sometimes like that:

<div id="q2">
    <label class="question_label">Label q2</label>
    <br>
    <input type ="text">
</div>

I have tied with prev() but sometimes there is a <br> between the input and the label, so prev doesn't always work. I also tried with closest() but it doesn't return the label:

$(':input').each(function () {
    alert($(this).closest('label').text());
});

What's wrong in my code ?

like image 788
Vincent Teyssier Avatar asked Nov 28 '22 01:11

Vincent Teyssier


1 Answers

DO it like this: ( Tested and Verified. )

$(':input').each(function () {
    alert($(this).parent().find('label').text());
});
like image 119
Atif Tariq Avatar answered Dec 15 '22 07:12

Atif Tariq