'Access Div Based on Another in JQUERY

How do I access the <a ....>General</a> base on this div I'm getting below on "test"?

test

<div
    role="tabpanel"
    class="panel-collapse collapse" 
    id="collapseGeneral"
    aria-labelledby="collapseGeneral"
    style="height: auto"
  >
    <div class="panel-body">
      ...
    </div>
  </div>

GIVEN

<div class="panel panel-default">
  <div role="tab" class="acc-heading" id="headingGeneral">
    <a
      data-toggle="collapse"
      role="button"
      aria-expanded="false"
      data-parent="#accordion"
      class=""                        
      href="#collapseGeneral"
      aria-controls="collapseGeneral"
      >General</a
    >
  </div>
  <div
    role="tabpanel"
    class="panel-collapse collapse" 
    id="collapseGeneral"
    aria-labelledby="collapseGeneral"
    style="height: auto"
  >
    <div class="panel-body">
      ...
    </div>
  </div>
</div>

code

  console.log(jQuery(test).parent(), "parent");


Solution 1:[1]

Looks like you want to find the matching aria-controls element for your <div>

Try this

// Find the matching aria-control
const control = $(`a[aria-controls="${test.id}"]`);

// Add the "collapsed" class
control.addClass("collapsed");

You could also match it by href but it wasn't exactly clear what your selection criteria was

const control = $(`a[href="#${test.id}"]`);

Here's a runnable demo...

// You don't need to redefine `test`,
// this is just emulating the variable in your question
// to make my answer runnable.
// IGNORE THIS LINE
const test = document.querySelector("#collapseGeneral");

// Find the matching aria-control
const control = $(`a[aria-controls="${test.id}"]`);

// now do something with `control`...
control.addClass("collapsed");
.collapsed { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<!-- minified HTML -->
<div class="panel panel-default"> <div role="tab" class="acc-heading" id="headingGeneral"> <a data-toggle="collapse" role="button" aria-expanded="false" data-parent="#accordion" class="" href="#collapseGeneral" aria-controls="collapseGeneral" >General</a > </div><div role="tabpanel" class="panel-collapse collapse" id="collapseGeneral" aria-labelledby="collapseGeneral" style="height: auto" > <div class="panel-body"> ... </div></div></div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1