Ways to determine whether LI contains UL descendants

I am trying to determine if a specific list item (LI) contains an unordered list (UL) inside of it using jQuery. Here is the code structure I am working with:

<ul>
    <li class="static">
        <ul class="static">
        </ul>
    </li>
    <li class="static"></li>
</ul>

My goal is to execute a certain action when a user clicks on an LI element that has a child UL. This is what I have attempted so far:

if(li has children ul)
{
    do something
}

UPDATE

Unfortunately, my current approach always returns "YES" for all cases. Below is the jQuery code and HTML sample I am working with. In this HTML snippet, only "Link2" has a child UL, while Link1 and Link3 do not. I simply want to perform a task when the user clicks on an LI element that contains a child UL.

JAVASCRIPT CODE

$('#DeltaPlaceHolderLeftNavBar div > div > ul > li > a').click(function()
{
   if($('li:has(> ul)'))
      alert("yes");
  else
     alert("no");
});

HTML SNIPPET

<div class="ms-core-navigation" id="DeltaPlaceHolderLeftNavBar">
 <div id="ctl00_PlaceHolderLeftNavBar_QuickLaunchNavigationManager">
  <div class=" noindex ms-core-listMenu-verticalBox" id="zz14_V4QuickLaunchMenu">
   <ul class="root ms-core-listMenu-root static" id="zz15_RootAspMenu">
    <li class="static">
     <a href="link1.php" tabindex="0" class="someclass1">
      <span class="someclass2">
       <span class="menu-item-text">Link1</span>
      </span>
     </a>
    </li>
    <li class="static">
     <a href="link2.aspx" tabindex="0" class="someclass3">
      <span class="someclass2">
       <span class="menu-item-text">Link2</span>
      </span>
     </a>
     <ul class="static">
      <li class="static">
       <a href="Link2A.php" tabindex="0" class="someclass1">
        <span class="someclass2">
         <span class="menu-item-text">Link2A</span>
        </span>
       </a>
      </li>
      <li class="static">
       <a href="Link2B.php" tabindex="0" class="someclass1">
        <span class="someclass2">
         <span class="menu-item-text">Link2B</span>
        </span>
       </a>
      </li>
     </ul>
    </li>
    <li class="static">
     <a href="Link3.php" tabindex="0" class="someclass1">
      <span class="someclass2">
       <span class="menu-item-text">Link3</span>
      </span>
     </a>
    </li>
   </ul>
  </div>
 </div>
</div>

Answer №1

It seems like in your specific code, utilizing this is necessary to reference the clicked element and then locate the parent <li> from there in order to target only the <li> that triggered the click event:

$('#DeltaPlaceHolderLeftNavBar div > div > ul > li > a').click(function() {
   if($(this).closest("li").children("ul").length) {
       // the clicked on <li> has a <ul> as a direct child
   }
});

In jQuery, you have the option to use either .find("ul") or .children("ul") depending on whether you want to target immediate descendants exclusively or any descendant.

For instance, if you wish to determine if a certain <li> tag with an existing reference contains a <ul> as a direct child, you can do this:

if ($(el).children("ul").length) {
    // el has a ul as an immediate descendant
}

Alternatively, if the <ul> could be any descendant, you can utilize this approach:

if ($(el).find("ul").length) {
    // el has a ul as a descendant at any level
}

If your objective is to simply identify all the <li> tags with <ul> beneath them, you have two choices:

You can retrieve a list of all <li> tags with a nested <ul> like so:

var tags = $("li").filter(function() {
    return $(this).find("ul").length !== 0;
});

If you specifically seek immediate descendants, you can employ this method:

var tags = $("li").filter(function() {
    return $(this).children("ul").length !== 0;
});

Subsequently, you can manipulate those particular <li> tags by directly invoking a function on the jQuery object without necessitating the if statement:

var tags = $("li > ul").addClass("hasSubMenu");

Answer №2

You have found exactly what you were searching for

$('li:has(> ul)');

JS Demo Link

Answer №3

Try using the :has selector

For example:

$('#DeltaPlaceHolderLeftNavBar div > div > ul > li > a').click(function () {
    if ($(this).closest('li').has('ul').length) {
        alert("The element has a nested ul");
    } else {
        alert("The element does not have a nested ul");
    }
});

Answer №4

If you're looking for direct children under your list items, you can use this code:

if($('li>ul').length > 0){

}

Alternatively, if you want to search the entire list item for a ul element, you can try this:

if($('li').find('ul').length > 0){


}

EDIT

I missed the word 'certain' in your original post, so here's an update:

If you have a structure like ul > li > ul, I've simplified it for better understanding. Here's an example of how it works:

HTML:
<ul>
    <li><a href="#">Level 1</a>
        <ul>
            <li><a href="#">Level 2</a></li>
        </ul>
    </li>

</ul>

JS:

$("ul>li>a").click(function(e){
    if($(this).parent().find('ul').length > 0){
     alert('Yeah, we have a ul');   
    }else{
     alert('Nope, no ul');   
    }
});

http://jsfiddle.net/Milanzor/NsPP7/ (Example with My HTML)

and http://jsfiddle.net/Milanzor/NsPP7/1/ (Example with Your HTML)

Answer №5

Another option is to utilize the length property

if($('li.dynamic').find('ul').length > 0) {
       //execute code here...
}

Answer №6

Checking if the immediate child of the current clicked list item (LI) contains an unordered list (UL), I utilize the following method to ensure that clicking on a submenu item does not collapse the previous menu:

HTML:

<nav>
    <ul>
       <li><a href="#">Item</a></li>
       <li><a href="#">Item</a></li>
       <li><a href="#">Item</a></li>
       <li><a href="#">Item</a>
             <ul>
                <li><a href="#">Sub Item</a></li>
                <li><a href="#">Sub Item</a></li>
                <li><a href="#">Sub Item</a></li>
             </ul>
       </li>
       <li><a href="#">Item</a>
             <ul>
                <li><a href="#">Sub Item</a></li>
                <li><a href="#">Sub Item</a></li>
                <li><a href="#">Sub Item</a></li>
             </ul>
       </li>
    </ul>
</nav>

Script:

var nav = $('nav');

nav.find('li>a').on('click',function(e){

    e.preventDefault();

    var $this = $(this);
    var $li = $this.parent();

    //set active state to clicked menu item:
    $li.addClass('active').siblings().removeClass('active open');

            //check for the presence of a UL after the A tag, indicating a submenu:
    if($this.next().is('ul')){
        $li.toggleClass('open');
    }

});

fiddle: https://jsfiddle.net/1fykp7wx/

Answer №7

Selecting the elements with class "shop-nav", then finding the child div, ul, and li elements, followed by a ul element. Then selecting the previous li element and adding an attribute of data-toggle with value "dropdown".

Answer №8

In my opinion, each approach caters to different needs. One possibility is to iterate through the list items (li) and check if they have unordered lists (ul) as children. If a list item contains a nested unordered list, you can modify its background color to red or customize it to your preference.

$('.top-menu > ul > li').each(function() {
    if ($(this).children('ul').length) {
        $(this).css('background', 'red');
    }
});

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 Jquery to target images within the viewport based on their class name

I have a webpage that contains various images. I'm looking to add an animation effect to these images when they come into view as I scroll down the page. Here is my current approach: $.fn.is_on_screen = function(){ var win = $(window); var vi ...

Modify the line graph's color according to the data, displaying red for values above a certain threshold (such as 0) and blue for values below 0

I am currently tackling a challenge involving displaying a graph that corresponds to the temperature of an object. My objective is to highlight sections of the line graph in red when the object's temperature is above 0, and in blue when it falls below ...

"Use jQuery to select all the cells in a row except for the

I found a visually appealing table layout that looks like this : https://i.stack.imgur.com/oRxYP.png What caught my attention is how clicking on a row selects the entire row. Take the example in the image above, where the second row is highlighted upon s ...

Center navigation bar text with the class `.justify-content-center`:

Can someone explain why, when I add the class justify-content-center to my Navbar in Bootstrap, the text remains in the left position? https://i.sstatic.net/8x0Yc.png I came across an instruction in the Bootstrap documentation stating that after adding t ...

Having difficulties linking my HTML form document to my PHP script

I have created a login form page on my website and am attempting to link it to a file named connect.php within the same directory. Here is the HTML content: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&q ...

Fade elements using jQuery on mouse click

As a newcomer to the programming world, I've been experimenting with jQuery and have a question about achieving a specific effect: To better understand my goal, please take a look at what I've attempted so far: http://jsfiddle.net/Whok7345/2wdda ...

Problem with handling success of AJAX form submission

I am encountering a problem where my AJAX form submission triggers an alert that seems to display the entire page instead of just the success message, and I am unable to pinpoint what I might be doing incorrectly. In addition, despite trying various sugges ...

When using React Router, make sure to set the navigation tab's style class to "active" if you are

I'm currently working on a React and react-router application that uses 2 nested routes to create a total of 3 routes: /, /about, /contact. When I click on the Links to navigate to each route, the tab on my navigation bar - which is located in the par ...

Is there a way to trigger this function with a button click event in Javascript, XSLT, XML, and HTML?

I need assistance with creating a webpage for my XML/XSL project that utilizes buttons to display country information when clicked. I initially achieved something similar using a dropdown list, but encountered issues when trying to implement buttons instea ...

Enhancing Responsive Design with Bootstrap 5: Using Different Alignments for Div Elements on Desktop

I have a unique layout design challenge for my bootstrap 5 website template. On desktop, I want to display divs in the following order: 1st line of divs: image, text 2nd line of divs: text, image https://i.sstatic.net/cXZVU.png When it comes to mobile ...

I'm currently facing some issues with switching my navigation bar on and off. I am utilizing the most recent version of Bootstrap, which is v5.1.3

Greetings! I'm new here and still learning the ropes, so please bear with me if I make some mistakes. I'm having an issue with my navbar-toggler not functioning as expected. I've tried various methods like adding older script sources and boo ...

A technique for making the placeholder flash when an input textfield loses focus

I am trying to implement a blinking effect on the placeholder text when the input field loses focus. Here is the HTML code I have written: <input type="text" id="keyfob" class="customform col-sm-12 text-red" data-required='true' placeholder= ...

What is the parent selector in cascading style sheets (CSS

Is there a way to use pure CSS to identify the parent selector of a child element? #checkbox{ width: 24px; height: 24px; vertical-align: middle; } #checkbox:checked (parentName){ color: red; } <label for="checkbox"> <input type="check ...

What is the reason behind Chrome's automatic scrolling to ensure the clicked element is fully contained?

Recently, I have observed that when performing ajax page updates (specifically appends to a block, like in "Show more comments" scenarios) Chrome seems to automatically scroll in order to keep the clicked element in view. What is causing this behavior? Wh ...

Choose an option removed upon clicking

I need to remove the option with a value of 0 when the user selects from the dropdown list. Choose: <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <form:select id="CONTEXTE" path="CONTEXTE" onclick="go()" class="s ...

Stop touchCancel during scrollStart action

When using an Android device, a scroll event triggers a `touchcancel` event, which prevents the touch up event from being triggered after scrolling. To avoid the `touchcancel` event, I implement a `preventDefault` on `touchStart` within the scrolling div. ...

Unlock AngularJS expression through ng-click functionality

I've encountered an issue with accessing AngularJS expressions after a click event takes place. index.html <div class="row"> <a href="#/company"><div class="tile col col-comp cat-a-g grow-appear" ng-click="onSelect(item)" ng-repea ...

The search functionality in an Html table is currently malfunctioning

Currently, I am working on developing a search mechanism in HTML. It seems to be functioning properly when searching for data for the first time. However, subsequent searches do not yield the expected results. Additionally, when trying to search with empty ...

Is it advisable to blend Angular Material with Bootstrap?

I'm brand new to Angular Material and it seems to have its own intricate API. Coming from using Bootstrap, I'm accustomed to utilizing its grid system with classes like row, containers, cols, etc. I'm curious if it's considered a good o ...