Locate the initial ancestor element that contains a specific child element on the first level

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.

Answer №1

li:has(input[type='checkbox']) will target all li elements that have an input nested within them, irrespective of the level.

In order to specifically select those li elements that directly contain a child input, use the direct descendant selector (>):

.parents("li:has(>input[type='checkbox'])")
.

To narrow down the selection to just one item, you can employ the .first() method.

$('input[type="checkbox"]').change(function(e) { 
  $(this)
    .parent()
    .parents("li:has(>input[type='checkbox'])")
    .first()
    .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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using PHP with Slim PHP Framework to dynamically include CSS files in the header of a document

I have developed a sleek application featuring a login form, dashboard, registration page, and account page. Each of these pages has its own unique route. To maintain consistency across all pages, I have included a shared header and footer by inserting < ...

I aim to generate a JavaScript string that, when placed within a div tag, will display as a list

I need assistance with formatting a string that contains a list of items to display in a specific way within a div tag using JavaScript. The string has multiple items that I wish to show as a bulleted list. Here is an example of the string: const items = & ...

Reverse the color of H1 text within a vertical div

Is it feasible to reverse the coloring of a segment within an h1 element using a div, horizontally? Refer to the illustration shown in the image below. https://i.sstatic.net/QAKwD.jpg ...

Making the Select Tag function as an on-click event in JQuery

So I currently have a tab set up that functions as on click links when viewed on desktop. However, for tablet and mobile devices, I need it to be transformed into a select drop down list while maintaining the same functionality. Below is the code used for ...

I am attempting to integrate the file path of my images using PHP

Let me start off by showing you the file structure of my website. File Structure Of my website In order to organize my code, I created a header file named header.html.php which contains all the necessary elements for the header, including an image tag fo ...

Ng-Zorro nz-range-picker resizing issue on smaller mobile screens

Currently using ng-zorro-antd 7.0.0 rc3 alongside angular 7.2.4. Encountering an issue where horizontal scrolling is not possible on mobile browsers when using the nz-range-picker. It appears that the element is too large for the screen, even though the p ...

A different option for incorporating interactive external content without using iframes

Excuse me for asking if this question has already been answered, but I was unable to find a solution that fits our specific needs. Is there a more effective method than using an iframe to embed external content in a website? Our objective is to provide a ...

Having trouble loading data.json file in React.js and jQuery intergration

Having a background in mobile development, I am relatively new to web development so please excuse any amateur questions. Currently, I am working on a react.js project using create-react-app (which utilizes Babel). I am following a tutorial that requires ...

Is there a way to retrieve the password of the currently logged in user using Keycloak in JavaScript?

Does anyone know how to access the password of a logged-in user in a React application using Keycloak? I have successfully retrieved most of the necessary information from the idToken, like this: keycloak.init({ onLoad: 'login-required'}).then(fu ...

How can I implement Jquery validation engine ajax for two different fields using the same function?

The jQuery validation engine plugin has a unique feature of performing ajax validation. However, there is a minor inconvenience with this functionality. Instead of validating the field name, it sends the field ID for validation. Why does this pose a prob ...

Get the identification number from a div located within an array of JSON objects using only JavaScript

I've scoured the internet for solutions to my problem, but nothing seems to work as I need it to. I've attempted various methods, including using href and button with the router, but unfortunately, none of them fit the specific requirements in th ...

Having trouble with ReactJS updating the state in the correct format using moment?

In my ReactJS project, I am using a datepicker feature. However, I have encountered an issue where the state is not being updated with the selected date value after formatting it using moment.js. const [selectedDates, setSelectedDates] = useState([]) ...

What is the best way to eliminate all text that appears after the final appearance of a character in JavaScript?

Suppose we have a specific string that looks like this: "A - B - C asdas K - A,B,C" Assume the character delimiter is "-" The goal is to extract everything before the last occurrence of "-", which in this case would be &quo ...

Tips for sending an Object within a multipart/form-data request in Angular without the need for converting it to a string

To successfully pass the object in a "multipart/form-data" request for downstream application (Java Spring) to receive it as a List of custom class objects, I am working on handling metadata objects that contain only key and value pairs. Within the Angula ...

Is it possible to use node.js and express in an application to redirect a URL and eliminate a file extension from the previous website?

We are in the process of transitioning our website from an ASP environment hosted on a Windows server. The current URL is http://www.bruxzir.com/video-bruxzir-zirconia-dental-crown/index.aspx However, I would like it to be http://www.bruxzir.com/video ...

Converting XML data (in SOAP format) to a JSON object using JavaScript

Can AJAX be used to send cross-site requests with a SOAP request and receive an XML response? Additionally, is there a framework similar to Mustache that can easily convert the XML response to JSON format? ...

Eliminating blank attributes within an array of objects

I'm currently working on a task that involves creating an array to summarize another array. I've received valuable suggestions from various sources, including this discussion on Stack Overflow. Although the solutions provided are effective, they ...

Identifying the presence of a mouse inside an element using jQuery

I am working on a website that utilizes jQuery. The structure of my page is as follows: <div id="page"> <!-- Content goes here --> <div id="content"> <div class="row"> <div class="col"><!-- content goes here ...

sending JSON information to the jQuery post function

Today I'm experimenting with a jQuery code snippet: $.post("test.php", { category: "Ubuntu", newname: "Hash" }, function(data) { alert("Data Loaded: " + data); }); My goal is to include form field data in the json request. In the past, I ha ...

Having trouble playing MP3 songs on Firefox with jPlayer?

I am facing an issue where the MP3 songs are not playing in Firefox even after trying the code below. Can someone help me with a solution? { title:"<?php echo $value['varsongName'];?>", mp3:"<?php echo $download; ?>", oga ...