To get the closest element by a selector, you can use the element.closest(). See the following example: const closestElement = targetElement.closest(selector); <ul id="parentElement" class="level-1"> <li id="ii"…