Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get specific element before THIS with jquery

Tags:

html

jquery

This really sounds simple, so i'm not sure where am I stuck. I have a form which I manually validate. after I check the radio buttons to be as required, I need to get the label above this element. Here is the HTML. I cannot change the markup as this code is an inheritance and part of a bigger process.

So this is my HTML:

<label>Do you market on? : </label>
<li>
    <label>Plenty of Fish:</label>
    <span href="#" style="float:  left; margin-right: 10px;">
        <input type="radio" class="required" name="data[SignupAnswer][100][answer]" value="yes" />Yes
    </span>
    <span href="#" style="float: left; margin-right: 10px;"> 
        <input type="radio" class="required" name="data[SignupAnswer][100][answer]" value="no" />No
    </span>
    <input type="hidden" name="data[SignupAnswer][100][signup_question_id]" value="100">
    <input type="hidden" name="data[SignupAnswer][100][class]" value="bool">
    <input type="hidden" name="data[SignupAnswer][100][required]" value="0">
    <input type="hidden" name="data[SignupAnswer][100][question]" value="Plenty of Fish">
</li>

I find the first radio, and then I need to find the label above it called "Plenty of Fish".

I tried with .prev(), and with .closest(), both with ('label'), but both didn't return an actual element but instead this object:

[prevObject: jQuery.fn.jQuery.init[1], context: <input>, selector: ".next(li)"]

Maybe someone can explain to me why I get this and not an element? and give me an idea how to get the required element? Thanks!

like image 681
Yanipan Avatar asked Feb 06 '26 08:02

Yanipan


1 Answers

closest selects the first closest parent element(specified by the selector), you can select the parent li element and then find the label:

$(this).closest('li').find('label')
like image 168
undefined Avatar answered Feb 07 '26 21:02

undefined