Looking to retrieve the primary parent element of a selected item that contains a checkbox as a direct child.
HTML
$('input[type="checkbox"]').change(function(e) {
$(this)
.parent()
.parents("li:has(input[type='checkbox'])")
.find(">span")
.css("background-color", "yellow");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<ul class="UL1">
<li class="LI1">
<input class="checkbox1" type="checkbox" />
<span>LI1</span>
<ul class="UL2">
<li class="LI3">
<input class="checkbox2" type="checkbox" />
<span>LI3</span>
</li>
<li class="LI4">
<input class="checkbox3" type="checkbox" />
<span>LI4</span>
<ul class="UL3">
<li class="LI5">
<span>LI5</span>
</li>
<li class="LI6">
<span>LI6</span>
<ul class="UL4">
<li class="LI7">
<span>LI7</span>
</li>
<li class="LI8">
<input class="checkbox4" type="checkbox" />
<span>LI8</span>
</li>
<li class="LI9">
<span>LI9</span>
</li>
</ul>
</li>
<li class="LI10">
<span>LI10</span>
</li>
</ul>
</li>
<li class="LI11">
<span>LI11</span>
</li>
</ul>
</li>
<li class="LI12">
<input class="checkbox5" type="checkbox" />
<span>LI12</span>
</li>
</ul>
</div>
NOTE: The code highlights the span for illustration purposes, but the main objective is to target the parent with a checkbox, not just any parent.
When selecting the checkbox within "LI8," the desired outcome is to identify its immediate parent with a checkbox, in this case "LI4." However, the current implementation returns all parent elements regardless of checkbox presence.
Is there a way to pinpoint only the initial parent containing a checkbox as a direct child? Ideally, when "LI8" is selected, only "LI4" should be returned while disregarding "LI6" and "LI1". Thank you.