Is there a child missing? If so, add a class

I need to add the class span.toggle if the parent element of li does not have a child ul element.

click here to view on codepen

Snippet of HTML:

<html lang="en">
<head>
    <meta charset="UTF-8>
    <title>No Title</title></head>

<body> 
    <ul>
        <li>
            <span class="toggle"></span><input type="checkbox" name="" id="0"><label for="0">Main 1</label>
              <ul>
                 <span class="toggle"></span> <li><input type="checkbox" name="" id="0-1"><label for="0-1">Child 1</label></li>
                  <span class="toggle"></span><li><input type="checkbox" name="" id="0-2"><label for="0-2">Child 2</label>
                      <ul>
                          <span class="toggle"></span>  <li><input type="checkbox" name="" id="0-1-1"><label for="0-1-1">Sub Child 1</label></li>
                            <span class="toggle"></span><li><input type="checkbox" name="" id="0-1-2"><label for="0-1-2">Sub Child 2</label></li>
                      </ul>
                  </li>
                 <span class="toggle"></span> <li><input type="checkbox" name="" id="0-3"><label for="0-3">Child 3</label></li>
                 <span class="toggle"></span> <li><input type="checkbox" name="" id="0-4"><label for="0-4">Child 4</label></li>
              </ul>
        </li>
        <li>
            <span class="toggle"></span> <input type="checkbox" name="" id="1"><label for="1">Main 2</label>
        </li>
    
        ...
        
    </ul>

<script type="text/javascript" src="https://cdn.anitur.com.tr/js/jquery-1.8.2.min.js" ></script>

</body>
</html>

CSS Styling:

 ul{
    list-style: none;
    padding:0;
    margin: 0;
    margin-left:20px;
    font:13px calibri;
}
input[type="checkbox"]{
    vertical-align:middle;
}

span.toggle{
    float:left;
    display:block;
    background:url("https://cdn3.iconfinder.com/data/icons/fatcow/16/bullet_toggle_plus.png") no-repeat 0px 1px;
    width:16px;
    height:16px;
}

ul> * ul {
    display:none;
}

input[type="checkbox"]:checked ~ ul {
    display:block;
}

JQuery Functionality:

$(function(){
    $("ul li").children("ul").each(function(){
        $(this).find("li").addClass("parentUl");
    });
});

Answer №1

$('ul > li').each(function(index, element){
    var ele = $(element);

    if(! ele.children('ul').length){
        ele.children('span').addClass('custom-class');
    }
});

Answer №2

Take a look at How to select elements without child nodes using jQuery

$('li'):not(:has(*)).addClass('classy');

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

Tips on obtaining checkbox value in an AJAX request

I need to retrieve the value of a checkbox using Ajax in order to store it as a user preference in the database. This task is new to me, and I'm feeling a bit overwhelmed. Here is my JavaScript file: $(document).ready(function() { E.accounts.chang ...

Utilizing JQuery AJAX and PHP for Data Encoding

My webpage is encoded in HTML with the charset ISO-8859-2. All content on the page adheres to this charset and appears correctly. However, I am facing an issue when making an Ajax call to a PHP server. When I send the character á and receive the same valu ...

Tips for ensuring all data is properly set before saving in mongoose

Struggling to update undefined or defined values in Mongoose due to the need to await their assignment. It seems like the code is not saving the data because USER.save() is executed before the values are set. How can I ensure that the data is updated/set ...

What are some methods for postponing a SurveyMonkey survey prompt?

Seeking feedback on a new site launch in beta mode (full launch scheduled for March 28). We want to give users time to explore the site before showing a pop-up after 10 seconds. As I am new to coding JavaScript, any assistance would be greatly appreciated. ...

What is the best way to navigate between elements using AJAX?

My experience in Ajax is minimal. I've managed to create two <li> elements with <a> elements inside, each linking to different HTML files. My goal is for clicking on a link to automatically load the corresponding HTML file without refreshi ...

Using Button Elements to Initiate Server Requests in Node.js

I'm currently in the process of designing a menu for my Node JS application and I'm struggling to find a way to send server requests without relying on the browser's navigation bar. Here is how my directory structure is organized: /applica ...

How can I make tooltipster display tooltips properly?

I have been struggling to customize tooltips using a library called tooltipster. Here is what I currently have: Head of index.html: <head> <!--TOOLTIP CSS--> <link rel="stylesheet" type="type/css" href="node_modules/tooltipster-master ...

What is the best method for fetching the values of a select element in React.js?

I'm struggling to retrieve the value of a selected element in a dropdown list. I've tried debugging it, but haven't been able to get the value. I attempted to console log e.target.value, but unfortunately, it didn't work. Any thoughts o ...

The interaction between jQuery and Rails through ajax calls

Attempting to work with basic functionality, Sending a request with data and receiving a response with data, then displaying it using jQuery and Rails This piece of code pertains to the frontend. $("#internal_btn").click(function() { //windo ...

Issues of horizontal spaces in HTML emails

We have been facing an ongoing issue with the layout of our email communications. Upon rendering in Outlook, the emails are displaying additional horizontal gaps/spaces. However, the web version of the email appears to be fine. It's unclear to us the ...

What techniques can I implement using JavaScript or CSS to create a slightly transparent effect on my text?

I am currently developing a website that features changing background images. I am looking to have the text on the site mimic the color of the backgrounds, but not so much that it becomes difficult to read. How can I make the text transparent in this man ...

I can't understand why my body width is so disproportionately larger than usual

https://i.stack.imgur.com/jbeyI.png Encountering a new issue now. The width of my body is unusually high and I can't seem to identify the cause. I have included the code below. Tried adjusting margins but no luck. Searched for solutions online wi ...

Tips for accessing the next sequential tag that is similar in HTML with the help of jQuery

I have generated the following HTML code from some plugins. <div class="parent"> <span>item1</span> <input type="hidden"></input> <span>item2</span> <span class="active">item3</span> <inpu ...

Achieving top-tier efficiency in segmenting items within an array of objects

Looking for a way to decrease the size of an array directly on my NodeJS server's memory. I aim to optimize network traffic by sending only the essential 'header' details of each object within the array. The current array on the server look ...

Beginning of my initial endeavor (seeking feedback, general advice, criticism)

Hey everyone! I'm looking for a forum-style platform similar to Stack Overflow where I can get some feedback on my first project. It's the first one I've built from scratch, so I'm open to any critiques or suggestions on what could be i ...

The technique of binding methods in React

When working with React.js, it's recommended to define your method binding in the constructor for better performance. Here's an example: constructor(props){ this.someFunction = this.someFunction.bind(this); } This approach is more efficient t ...

Arranging buttons in a row with Bootstrap 5

Struggling to align the buttons on my webpage side by side in the center, I've tried two Bootstrap 5 classes but they're not achieving the desired look: https://gyazo.com/c23f2eade4614380aec547b11e61387a https://gyazo.com/e40a678b02c9f641f746b1c ...

What is the best way to incorporate a state variable into a GraphQL query using Apollo?

My current challenge involves using a state as a variable for my query in order to fetch data from graphQl. However, I'm encountering an issue where the component does not read the state correctly. Any suggestions on how to solve this? class usersSc ...

The Ajax request functions correctly in Chrome and Safari but encounters issues in Firefox and Internet Explorer

I've encountered an issue with jQuery where the call is failing when making a request with base64 authorization header in the beforeSend function. It's a simple request to retrieve projects. function GetProjects(full){ var query = "/Projects"; $ ...

Tips for utilizing canReuse and routerOnReuse in Angular 2

I've reviewed the information provided in this link, but I'm still unsure about how to effectively utilize it. My requirement is straightforward—I need to update a parameter in the URL without constantly sending API requests, which are current ...