简体   繁体   中英

How to target next() in the same div

I have this HTML :

  <h3 class="toggle_div">
        <i class="left-image switch-icon"></i>
  </h3>

I want to change classnames when I click on the div . In this case, left-image should change to a classname right-image .

This is the jQuery I have:

$('.toggle-div').click(function(){
     $(this).siblings().next('.switch-icon').toggleClass("left-image right-image");
});

I tried this, because the code beneath only works if I put the <i> element underneath the div element I want to use to toggle. So it seems like I can't get the classname of the element that is within the div element.

$('.toggle-div').click(function(){
     $(this).next('.switch-icon').toggleClass("left-image right-image");
});

What can I use to make it work?

JSFiddle : http://jsfiddle.net/f72FY/69/

First of all your class name is wrong in JS. and then you don't need $(this).siblings().next

Just try this

$('.toggle_div').click(function(){
     $('.switch-icon').toggleClass("left-image right-image");
});

You can use .find() to find .switch-icon within the element which is clicked

  $('.toggle_div').click(function(){ $(this).find('.switch-icon').toggleClass("left-image right-image"); }); 
 .left-image { background-image: url('http://i.stack.imgur.com/euD9p.png'); width:20px; height:20px; background-repeat: no-repeat; } .right-image { background-image: url('http://i.stack.imgur.com/dzs9m.png'); width:20px; height:20px; background-repeat: no-repeat; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h3 class="toggle_div"> Clicking on this text should toggle <div class="left-image switch-icon"></div> </h3> 

You may use .children Or .find with in the method. That should be able to retrieve the full element details based on selector.

Try this code

$('.toggle_div').click(function(){
                  $('div.switch-icon').toggleClass("left-image right-image");
    });

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