1

I need to add a class to an element outside the ancestry. The following method does the task, however I'd like to lessen the use of parent() instances.

The code

<h4 class="tab">Title</h4>
<div>
  <div>
    <div>
      <div>
        <ul>
          <li><p class="send">add class to h4 from here</p></li>
        </ul>
      </div>
    </div>
  </div>
</div>

<script>
jQuery(function($) {
  $(".send").parent().parent().parent().parent().parent().parent().prev().addClass("active");
});
</script>

I tried

All the following efforts fail to return the desired result.

$(".send").closest(".tab").addClass("active");

$(".send").find(".tab").addClass("active");

Update for clarity

The method is used for a slide down accordion where items are selected by the client, and each tab is highlighted if there are item(s) chosen. Also I have no control over the elements so I cannot add or remove classnames, and the structure is exactly as shown. I am just adding this method as a dynamic modification of the extension.

enter image description here

Nadal
  • 105
  • 7
  • May I ask why you can't just use `$(".tab")` – fortunee Apr 03 '21 at 07:49
  • Can't you add a global container for the selection? – mchev Apr 03 '21 at 07:57
  • I assume you are trying to create some sort of edit modal where in data is grabbed dynamically from the dom, in that case my answer to a similar requirement should help, note that it is for a table but the same concepts still apply. https://stackoverflow.com/a/48863079/2757519 – Dev Man Apr 03 '21 at 08:19
  • @fortunee the sending element only adds the class on a user action. I just did not include all the other coding that shows the whole process. It is quite long. Hence the reason I can't just use `$('.tab')` – Nadal Apr 03 '21 at 09:13
  • Does this HTML will be repeated? – Bhautik Apr 03 '21 at 09:20
  • @Ainz-sama it is a slide accordion or drop down, and within each container, the user initiates an action with the `.send` element and the tab should receive the class to indicate that it is active, so the user is not guessing which closed slide was used. – Nadal Apr 03 '21 at 09:26
  • @Bhautik yes the HTML is repeated numerous times and only the

    and inner

  • content changes. All the element classes remain constant.
  • – Nadal Apr 03 '21 at 09:28
  • @mchev I don't see how a global container would resolve the case. – Nadal Apr 03 '21 at 09:29
  • Can you update HTML as well with repeat?t – Bhautik Apr 03 '21 at 09:43
  • @Bhautik no I cannot alter the HTML, it's a third party extension and I am just adding a method to create alerts. Please see the updates in my original post for some clarity. – Nadal Apr 03 '21 at 09:47
  • But you can inspect that HTML and you can see how it's rendered. – Bhautik Apr 03 '21 at 09:58