Search code examples
javascriptjqueryaccordionjquery-ui-accordion

accessing the parent accordion in nested accordion


<li>
  <a class="toggle" href="javascript:void(0);" id="plus">ABC</a>
  <ul class="inner">
    <li>
      <a href="#" class="toggle" id="plus">DEF</a>
      <div class="inner" id="mixedFaVT">
      </div>
    </li>
    <li>

      <a href="#" class="toggle" id="plus">GHI</a>
      <div class="inner" id="mixedFaVA">
      </div>
    </li>
  </ul>
</li>

How do I access ABC, when $this = DEF or $this = GHI? The problem is, there are five other sets of nested accordions, in the same HTML page. To generalize the question, when $this is any 'inner' button like DEF/GHI, how do I access their particular parent ABC using jQuery? I have tried .find() and .parents(), but those do not work.


Solution

  • You may traverse the parents of $this until the ul using the parents() method, and then get the previous element of it, which will be the a.

    var $this = $('#plus-1');
    var parent = $this.parents('ul').prev();
    
    console.log('$this:', $this.text());
    console.log('parent:', parent.text());
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <li>
      <a class="toggle" href="javascript:void(0);" id="plus-0">ABC</a>
      <ul class="inner">
        <li>
          <a href="#" class="toggle" id="plus-1">DEF</a>
          <div class="inner" id="mixedFaVT">
          </div>
        </li>
        <li>
    
          <a href="#" class="toggle" id="plus-2">GHI</a>
          <div class="inner" id="mixedFaVA">
          </div>
        </li>
      </ul>
    </li>