简体   繁体   中英

How to select a div based on a checked input box in an adjacent div

Given the code segment below, is there a way to write a CSS selector that targets the div of class="item_text" provided that the checkbox is checked?

 <div class="row"> <div class="col-xs-1"> <input name="item_checkbox" type="checkbox" /> </div> <div class="col-xs-11"> <div class="item_text" contenteditable="true"> To rearrange your list, drag and drop items </div> </div> </div> 

As has been stated in the comments, it's not possible to do this in CSS alone as CSS rules cannot traverse up the DOM.

As you've tagged the question with jQuery, you could use that instead to affect the required element when the checkbox state is changed. Try this:

 $('.row :checkbox').change(function() { $(this).closest('.row').find('.item_text').toggleClass('foo', this.checked); }); 
 .foo { border: 1px solid #C00; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="row"> <div class="col-xs-1"> <input name="item_checkbox" type="checkbox" /> </div> <div class="col-xs-11"> <div class="item_text" contenteditable="true"> To rearrange your list, drag and drop items </div> </div> </div> 

This is possible . I just rearranged the dom slightly then added some css:

 input[name=item_checkbox]:checked + div.item_text { display:none; } 
 <div class="row"> <div class="col-xs-11"> <input name="item_checkbox" type="checkbox" /> <div class="item_text" contenteditable="true"> To rearrange your list, drag and drop items </div> </div> </div> 

这仅适用于jQuery / jQuery,因为CSS选择器无法向上遍历(从子级到父级)。

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