2

For the span element with the class "arrows", I'm trying to add a class to the div with the class "collapse" from its parents and also an attribute to the div with the class "navbar-toggler".

I tried the following code:

$(function() {
  $('.arrows[aria-expanded="true"]').closest('.navbar-toggler').setAttribute("aria-expanded", true);
});

$(function() {
  $('.arrows[aria-expanded="true"]').parents('.collapse').addClass('in')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="navbar-toggler collapse-icons" data-toggle="collapse" data-target="#exCollapsingNavbar10">
  <i class="material-icons add"></i>
  <i class="material-icons remove"></i>
</div>

<div class="collapse" id="exCollapsingNavbar10">
  <ul class="category-sub-menu">
    <li data-depth="1" data-id="11">
      <a class="category-sub-link" href=" ">Educație Arduino</a>
      <span class="arrows" data-toggle="collapse" data-target="#exCollapsingNavbar11" aria-expanded="true">

4
  • You miss the reference on which to target. If there are multiple ones, you need to refer to this (as in the element clicked) and then move the way up. Commented May 24, 2023 at 11:03
  • Did you see the error in the console? setAttribute() is a native JavaScript method. You can't invoke it on a jQuery object. Use attr(). Commented May 24, 2023 at 12:57
  • Note that you don't need multiple ready() functions. Put all your code in one. Commented May 24, 2023 at 12:58
  • I had no errors in console, but I'll keep that in mind, thank you! I'm new to this and still learning Commented May 25, 2023 at 6:16

1 Answer 1

1

$('.arrows[aria-expanded=true]')
  .parents('.collapse')
  .addClass('in')
  .prev()
  .attr('aria-expanded', true);
.in {
  background: yellow;
}

.navbar-toggler[aria-expanded=true] {
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="navbar-toggler collapse-icons" data-toggle="collapse" data-target="#exCollapsingNavbar10">
  <i class="material-icons add"></i>
  <i class="material-icons remove"></i>
</div>

<div class="collapse" id="exCollapsingNavbar10">
  <ul class="category-sub-menu">
    <li data-depth="1" data-id="11">
      <a class="category-sub-link" href=" ">Educație Arduino</a>
      <span class="arrows" data-toggle="collapse" data-target="#exCollapsingNavbar11" aria-expanded="true"></span
    </li>
  </ul>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.