I'm struggling to adjust the height of a div based on whether a list item within it contains a nested unordered

I have been working on a horizontal menu that is functioning well for me. However, according to the design requirements, I need to adjust the height of

<div id="nav-subMenu"></div>
if the main/parent menu li does not have any submenus or ul. The jQuery code that I have written for this purpose is not working as expected. Any assistance in resolving this issue would be greatly appreciated.

For reference, here is an example on jsFiddle

if ($('#nav-wrapper ul li').has('ul'))
always returns true.

Sample jQuery Code:


jQuery(document).ready(function () {

    if ($('#nav-wrapper ul li').hasClass('active')) { //if it has the "active" class
        if ($('#nav-wrapper ul li').has('ul')) {
            alert('aaaa');
            $('#nav-subMenu').css("height", "30");
        }
    }
});

Sample HTML Code:

<div id="nav-wrapper">
   <ul class="dropdown dropdown-linear" id="nav">
      <li><span class="dir"><a href="#">Home</a></span></li>
      <li><span class="dir"><a href="#">About Us</a></span></li>
      <li><span class="dir"><a href="Articles.aspx?PageID=5&amp;Language=en-us&amp;ParID=0&amp;Issue=5&amp;CID=1">Articles</a></span></li>
      <li class="active">
         <span class="dir"><a href="Page.aspx?PageID=6&amp;Language=en-us&amp;ParID=0&amp;Issue=5&amp;CID=1">Categories</a></span>
         <ul>
            <li><a href="Page.aspx?PageID=6&amp;Language=1&amp;ParID=6&amp;Issue=1&amp;CID=18">Book Review</a></li>
            <li><a href="Page.aspx?PageID=6&amp;Language=1&amp;ParID=6&amp;Issue=1&amp;CID=16">Business</a></li>
            
            (Other list items omitted for brevity)
            
         </ul>
      </li>
      
      (Other list items omitted for brevity)
      
   </ul>
</div>
<div id="nav-subMenu"></div>
<div id="NewsTicker"> </div>

UPDATE: Firebug gives a view to help understand when the jQuery should trigger to adjust the height of the DIV.

Answer №1

Your issue has been addressed and resolved according to your requirements. Please test out the following solution:

jQuery(document).ready(function () {
  if ($("#nav-wrapper li.active").length) {
    alert('yes, there are elements with the .active class');
    if ($(".active").has('ul').length) {
      alert('yes, elements with the .active class have ul');
      $('#nav-subMenu').css("height", "60px");
    } else {
      alert("NO, elements with the .active class do not have ul");
      $('#nav-subMenu').css("height", "0px");
    }
  } else {
    alert("NO elements with the .active class were found.");
  }
});

You can view and test this solution in action on JSFiddle here: http://jsfiddle.net/zMty8/27/

Answer №2

Take a look at this piece of code:

$(document).ready(function () {

    if (!$('#nav-wrapper ul li').hasClass('active')) { //check if it does not have the active class
        if ($('#nav-wrapper ul li > ul'.length > 0) {
           $('#nav-subMenu').css("height", "30");
        }
    }
});

DEMO

Answer №3

Give this a shot:

if ($('#nav-wrapper ul li').has('ul')) {
     $('#nav-subMenu').css("height", "30px");
}
if ($('#nav-wrapper ul li').has('ul')) {
    alert('a');
    $('#nav-subMenu').css("height", "30px");
}

Check out the documentation here

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

"Receiving the error message 'Object is not a function' occurs when attempting to pass a Node.js HTTP server object to Socket.IO

A few months back, everything was working fine when I set up an HTTPS server. Recently, I revisited the application and decided to switch to HTTP (though this change may not be directly related). In my code snippet below from 'init.js', I create ...

Calculate the total sum of a specific property within an array using ES6

My goal is to calculate the total unit value by date and create a new array without duplicate dates. For instance, I want to sum up the values of 2015-12-04 00:01:00. This particular date appears twice in the dataset with values of 5 and 6, resulting in: ...

Achieving the equivalent of php crypt() in NODE.JS

Can anyone assist with converting PHP to JavaScript (Node.js)? $key = crypt($key, $salt); I am currently in the process of rewriting a PHP script using Node.js, and I have encountered an issue with generating hash signatures similar to the ones created b ...

Retrieve data from a different div, perform a subtraction operation, and dynamically update yet another div using jQuery

Looking to extract a specific div class value, subtract 500 from it, and display the result in another div. Unclear about the steps needed to show the subtraction outcome on the other div. Consider this scenario: <div class="main-value">6000</d ...

When transferring Next Js static assets to Plesk, a 500 internal server error is encountered

I've successfully deployed a Next.js app to Plesk hosting after a lot of troubleshooting. However, I'm encountering 500 internal server errors in the console when trying to access the static assets. Here's an example: GET https://nextjs-test ...

Tooltips for Images in Vega Charts

As a developer skilled in d3, I am navigating the world of VEGA charts and seeking guidance on how to incorporate an image in a tooltip. Do you have any suggestions for me? For example, considering this particular scenario: If we assume there is an addit ...

When a user clicks on an anchor tag, the corresponding value of the checked item is then returned

I have 3 sets of radio buttons. When a specific anchor with the "round" class is clicked, two actions should occur: The associated set of radio buttons needs to become visible The value of the checked input for that element should be returned. I am ...

Is it possible to combine the existing request parameters with a new parameter in JSP/JSTL/JQuery?

Here is a sample URL: http://127.0.0.1:8080/admin/seller?email=tim%40example.com Below is a snippet of JSP code: <a class="btn btn-primary ${page==pages||pages==0?'disabled':''}" href="?page=${page + 1}">Next</a> I am ...

Performing an asynchronous HTTP request using AJAX and jQuery's post or get methods

Currently embarking on the creation of a PHP, MySQL, AJAX, and JQuery-powered calendar. While my expertise in the latter two technologies is lacking, I am eager to expand my knowledge. I stumbled upon a script that fulfills my basic requirements, but I hav ...

What is the best way to transfer the value of a slider from jQuery or JavaScript to a Python Flask application

Trying to implement a round slider that displays its value on the client-side webpage. Whenever the user adjusts the slider, the updated value needs to be sent to the server using Python Flask as the backend. I attempted to achieve this using jQuery and Aj ...

The process of filtering a model stops at the third character and results in an empty output

Whenever I input a value into the 'temp_dollars' model and use a watch property to filter it, the input only retains the first 3 characters and resets. For instance: When I type 123, The model value remains as 123. But wh ...

Unable to attach an event listener to an element fetched from an API

I'm currently in the process of developing a trivia web application using an API, and my goal is to incorporate an event listener onto the button which corresponds to the correct answer. This way, when users click on it, a message will appear confirmi ...

Obtain all values from multiple Selectize instances sharing the same class using JavaScript

I have an HTML page containing multiple selects (created with selectize) all sharing the same class "idPeople". When I click the "search" button, I need to retrieve all the values from these selects. However, in my JavaScript file using ...

Double invocation of useEffect causing issues in a TypeScript app built with Next.js

My useEffect function is set up with brackets as shown below: useEffect(() => { console.log('hello') getTransactions() }, []) Surprisingly, when I run my app, it logs "hello" twice in the console. Any thoughts on why this might be ...

What is the best method to pass a JavaScript file array to a Node.js server?

Is it possible to transfer data from a Javascript file linked to an HTML page to a Node.js file on a post route without displaying it on the HTML page? If so, what is the best way to accomplish this? ...

What is the appropriate way to retrieve an array that has been stored in the this.state property?

https://i.stack.imgur.com/y9huN.jpgAs a newcomer to react, I have been exploring the react documentation on making Ajax calls. While the docs make it seem simple to retrieve JSON information and set it to a state variable, I've encountered some challe ...

Difficulty encountered while integrating chart.js with Django using npm

Encountering an issue while using Chart.js in my Django project - when utilizing the NPM package, it fails to work. However, switching to the CDN resolves the problem seamlessly. Chart.js version 3.9.1 Below is a snippet from my project's index.html ...

Apply the active class to only one element at a time

Presented here is a table showcasing available dates and times. Users can select a specific time by clicking on the "Choose" link. Currently, when a user selects a time, the class "active" is applied. However, the desired behavior is to remove the previous ...

On smaller screens, the top placement of right sidebar links is necessary

Our website layout is organized into 3 main sections: the top part contains the main menu, followed by the main content and a sidebar specific to each page. The main content and sidebar are structured using bootstrap col-* classes. On small screens, I en ...

I have a Key in my component, but it is still searching for a unique key

Just diving into React JS and attempting to transfer data from one component to another using the Link to method I found online... Error: index.js:1 Warning: Each child in a list should have a unique "key" prop. Checking the render method of Videos. Refe ...