Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery closest with attribute filter

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?

enter image description here


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?

like image 706
Adam Rackis Avatar asked Feb 05 '12 01:02

Adam Rackis


People also ask

How get data attribute value in jQuery?

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" ).

Is closest JavaScript or jQuery?

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.

What jQuery syntax selects HTML elements by a specific attribute and its value?

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").


2 Answers

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);
like image 127
nnnnnn Avatar answered Sep 29 '22 08:09

nnnnnn


Check for: http://api.jquery.com/closest/

.closest( selector ) // version added: 1.3
like image 38
DraganS Avatar answered Sep 29 '22 07:09

DraganS