Does jQuery 1.5.1 support attribute selectors in the closest method?
Given the structure below, el
represents the checkbox with the value 513, and I'm trying to reach up and check the ancestor checkbox with the value of 0 with
$(el).closest("input[value='0']")[0].checked = true;
but the selector is returning nothing.
Am I missing something silly?
EDIT
Sigh, so the checkbox with value 0 isn't an ancestor to el
, just a sibling of the ul
ancestor. I got it to work with
$(el).closest("ul").siblings("input[value='0']")[0].checked = true;
But us there a cleaner way to grab it?
To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).
The closest() is an inbuilt method in jQuery that returns the first ancestor of the selected element in the DOM tree. This method traverse upwards from the current element in the search of first ancestor of the element.
jQuery [attribute|=value] Selector The [attribute|=value] selector selects each element with a specified attribute, with a value equal to a specified string (like "en") or starting with that string followed by a hyphen (like "en-us").
The .closest()
method does support attribute selectors the same as any other jQuery method (although I don't know about the specific version of jQuery you mentioned), but the problem here is that .closest()
doesn't just look in the general vicinity, it goes up through the ancestors. You are trying to select an input element that is not an ancestor of the element you are starting with. (Given that inputs can't contain other elements they will never be the ancestors of anything...)
You should be able to do it by selecting the target checkbox's parent li element first:
$(el).closest('li:has(input[value="0"])')
.find('input[value="0"]').prop("checked",true);
Demo: http://jsfiddle.net/Vpzyj/
Of course if you were able to add a class to the top level menu items you wouldn't need to mess around with ":has", you could just say:
$(el).closest('li.topMenu').find('input[value="0"]').prop("checked",true);
Check for: http://api.jquery.com/closest/
.closest( selector ) // version added: 1.3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With