Find Index of First Parent with Class

488 Views Asked by At

I've got a jQuery Accordion where every panel is represented by a <div> element with the class .ui-accordion-content. Every panel has a form inside of it. On each form's submit event, I would like to open up the next panel.

I would like to travel up the DOM tree from the form, find the first div with the class .ui-accordion-content, and return its index on the page, so I know which form was "submitted" and which panel to open up next.

The here's the function I wrote:

$("form").each(function () {
    $(this).submit(function (e) {
        e.preventDefault(); // this will prevent from submitting the form.
        $("#accordion").accordion({ active: $(this).closest(".ui-accordion-content").index() });
        return false;
    });
});

It doesn't return the correct indices. What's going wrong?

EDIT: Here is the HTML:

<div id="Accordion">

    <h3 class="ui-accordion-header"></h3>
    <div class="ui-accordion-content FormOne">
        <form>
        </form>
    </div>

    <h3 class="ui-accordion-header"></h3>
    <div class="ui-accordion-content FormTwo">
        <form>
        </form>
    </div>

</div>
3

There are 3 best solutions below

0
On BEST ANSWER

You need to filter out selection regarding .ui-accordion-content elements only. So pass selector param of jQuery's .index() method and add 1 to get the next one:

active: $(this).closest(".ui-accordion-content").index(".ui-accordion-content") + 1

0
On

You can use parents and find the first .ui-accordion-content.

$("form").each(function () {
  var self = $(this);
  self.submit(function (e) {
    var _index = self.parents('.ui-accordion-content:first').index();
    e.preventDefault(); // this will prevent from submitting the form.
    $("#accordion").accordion({ active: _index });
    return false;
  });
});
1
On

You can use the .parents() selector to traverse up the tree and find the matching parent.

$(this).parents(".ui-accordion-content").index()