简体   繁体   中英

jQuery - How do you select a parent based on the attribute of a child?

How do you select a parent based on the attribute of a child?

I want to select a div:

that has a child with the radio:checked

<div> <input id="1" type="radio"/> </div>
<div> <input id="2" type="radio"/> </div>

for example.

$('div radio:checked').click(function(){
     $(*** div parent based on radio:checked ***).css({'background':'#F00'});
});

closest()

$('div radio:checked').click(function(){
    $(this).closest('div').css({'background':'#F00'});
});

if you want the nearest 'parent' div, even if it is several levels up.

parent()

$('div radio:checked').click(function(){
    $(this).parent('div').css({'background':'#F00'});
});

if you want the direct parent

Interestingly, you can do a sort of reverse lookup selector with :has like

$('div:has(radio:checked)').click(function(){
    $(this).css({'background':'#F00'});
});

try:

$('div radio:checked').click(function(){
 $(this).parent().css({'background':'#F00'});
});

UPDATE:

the 'div radio:checked' do not work in your code, you can use:

$('div input[type=radio]').click(function () {
 $(this).parent().css({'background': '#F00'});
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM