Search code examples
javascriptjqueryindexingtoggleclass

JQuery ToggleClass using index attribute


I have a toggle functionality to implement in my page. I want to show a label next to span element. But the problem is I need to trigger only corresponding labels

Here is my HTML code

    <div>
        <span class="header1">Header</span>
        <label class="dtl1 hide  ">Details</label>
        <span class="header2">Header</span>
        <label class="dtl2 hide">Details</label>
    </div>


Javascript code

    $('span').click(function() {
      var selIndex =  $("span").index(event.currentTarget);
      $('label').toggleClass("hide");
    });

Do we have anything like next().toggleClass() or use Index of both elements and apply toggleClass


Solution

  • There are several errors in your code. Your callback doesn't accept the event object. So you are using the global event object (in some browsers) not the current event, which can't be reliable. You are also missing the . for the toggleClass call and ) for closing the click method.

    That being said, if you want to select the very next label sibling of the clicked span you can use the next method:

    $('span').click(function(event) {
       // event.currentTarget is typically equal to `this` in this context
       $(this).next('label').toggleClass("hide");
    });
    

    If you want to use the index method, you should also use the eq method:

    $('span').click(function(event) {
        var index = $("span").index(event.currentTarget);
        $('label').eq(index).toggleClass("hide");
    });