tags:

views:

39

answers:

2

Hello all,

<li id="ll">
    <li id="li_1" >
        <label class="description" for="element_1">First Name </label>
        <div>
            <input id="element_1" name="element_1" class="element text medium" type="text"/> 
        </div> 
    </li>
</li>

Given element 'element_1', how to select its first parent with tag name as li?

Thank you

+3  A: 

$('#element_1').closest('li').addClass('testclass');

tvanfosson
Thank you very much tvanfosson!
q0987
+4  A: 
$('#element_1').closest('li').addClass('testclass');

assuming you're using jQuery 1.3+ and element_1 is an ID.

jQuery < 1.3 should look like

$('#element_1').parents('li').addClass('testclass');

Reference: .closest(), .parents()

jAndy
I'm pretty sure closest() was in 1.3+
tvanfosson
jAndy - You probably should have the `:first` selector for the `.parents()` version in case of nested lists.
patrick dw
@patrick: that would mean multiple unique ID's in the markup right?
jAndy
@tvanfosson: fixed that
jAndy
@jAndy - No, I mean for the `li`, as in `.parents('li:first')`. If there are nested lists, using `.parents()` will add the class to *all* the ancestor `<li>` elements. That way it more accurately emulates `.closest()`.
patrick dw
Many thanks jAndy
q0987
Hello patrick,your solution is the one that i am looking for.
q0987