简体   繁体   中英

selectors not and siblings

I have 3 divs and each have one black and red rectangle. I want that when you click on one of the black rectangles all the reds will change the color to white except the red one that is sibling of the black clicked. I don't want to add any more classes ids or change the dom. I've been trying with no success. thx in advanced.

  $(document).ready(function(){ $(".black-rectangle").click(function(){ $(".red-rectangle").not(this.siblings(".rec2")).css("background-color","#fff"); }) }) 
  .black-rectangle{ height: 50px; width: 50px; background-color:#000; border: 5px solid green; margin-top: 10px; } .red-rectangle{ height: 50px; width: 50px; background-color: red; border: 5px solid green; margin-top: 10px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <body> <div> <div class="black-rectangle"></div> <div class="red-rectangle"</div> </div> <div> <div class="black-rectangle"></div> <div class="red-rectangle"</div> </div> <div> <div class="black-rectangle"></div> <div class="red-rectangle"</div> </div> </body> 

siblings is a jQuery method, but this is a DOM element, not a jQuery object. You need to use $(this) to wrap it in a jQuery object.

There's no rec2 class in your HTML, so I changed it to just .siblings() with no selector.

 $(document).ready(function() { $(".black-rectangle").click(function() { var $this = $(this); $(".red-rectangle").not($this.siblings()).css("background-color", "#fff"); }) }) 
 .black-rectangle { height: 50px; width: 50px; background-color: #000; border: 5px solid green; margin-top: 10px; } .red-rectangle { height: 50px; width: 50px; background-color: red; border: 5px solid green; margin-top: 10px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <body> <div> <div class="black-rectangle"></div> <div class="red-rectangle"></div> </div> <div> <div class="black-rectangle"></div> <div class="red-rectangle"></div> </div> <div> <div class="black-rectangle"></div> <div class="red-rectangle"></div> </div> </body> 

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