How can I use JavaScript to modify the style of the first unordered list (ul) element without affecting the

function displayMenu(){
var parentElement = document.getElementById("menuItem1");
var lis = parentElement.getElementsByTagName("ul");
for (var i = 0; i < lis.length; i++) {
lis[i].setAttribute("style","display: block");
}   
}

When the button is clicked, I want to show only the first ul item. Instead of using :hover in my webpage to display the ul's, I am trying to use javascript to show the menu onclick. While I am not an expert in JavaScript, I am beginning to understand it gradually. However, I am still struggling with this piece of code. I attempted to assign unique IDs to the main li's of the top ul like menuItem1 and menuItem2, which made it possible to show the ul's for only that specific li, achieving my desired outcome of not opening both.

The issue lies in displaying every under-menu as well, indicating that I might have overlooked instructing it to affect only the first ul, not each child. I comprehend the overall logic behind it, but I am unfamiliar with JavaScript commands such as first.child. Any suggestions on how to steer me in the right direction?

I grasp the concept of obtaining the element with ID in this function, and comprehending Tagname is straightforward. However, the rest remains unclear to me. Although I realize it iterates through the objects, I do not quite understand why or what it does with them.

So, is there a way to impact solely the first ul without influencing every sub-category?

While CSS and HTML are working smoothly, perhaps there is another approach to achieve this without altering the three main Li's to have unique IDs?

This is a glimpse of my menu structure:

<nav id="cssmenu">
<ul>
<li id="menuItem1"><a href="">menuItem1</a>
    <ul>
    <li><a href="">submenu1, no unique ID</a></li>
    <li><a href="">submenu1, no unique ID</a></li>
    </ul>
<li id="menuItem2"><a href="">menuItem2</a>
    <ul>
    <li><a href=''>submenu2, no uniwue ID</a></li>
    <li><a href=''>submenu2, no unique ID</a>
  *      <ul>
        <li><a href=''>submenu2-2nd column, no unique ID</li>
  *      </ul>
    <li><a href=''>submenu2, no unique ID</a></li>
    </ul>
</ul>
</nav>

I marked a * where my ul that should not be opened is located. Is there any solution to this problem without assigning unique IDs to each ul? I gave the top-li's individual IDs such as menuItem1, etc., and would prefer not adding more unique IDs to my menu since it is rather extensive across many pages.

Additionally, I prefer using JavaScript over jQuery as I have yet to grasp the utilization of jQuery.

EDIT: Added IDs to my li's where necessary. Would utilizing addEventListener make this task simpler? Though unfamiliar with it, could I set actions for the first click and then close the menu with the second click? Thank you in advance for your assistance!

RE-EDIT: The code provided worked correctly, just did not hide the ul's again.

function Meny(){ 
var parentElement = document.getElementById("cssmenu"); 
var lis = parentElement.getElementsByTagName("ul"); 
for (var i = 0; i < lis.length; i++) { 
lis[i].setAttribute("style","background: red"); } } 

However, tweaking it to display:none hides the entire thing, resulting in my menu disappearing, which is not ideal. Can someone explain how this works? I must have missed something crucial, considering my limited understanding of JavaScript.

Answer №1

To begin, consider removing the loop in your javascript code and passing an argument that points to the clicked DOM element (in this case, the li):

function showMenu(parentElement){
    var uls= parentElement.getElementsByTagName("ul");
    if (uls.length > 0)
        uls[0].setAttribute("style","display: block");
}

Next, utilize the onclick attributes of the li tag by calling the showMenu function with 'this' as the argument:

<nav id="cssmenu">
<ul>
<li id="menuItem1" onclick="showMenu(this)"><a href="#">menuItem1</a>
    <ul>
    <li><a href="#">submenu1, no unique ID</a></li>
    <li><a href="#">submenu1, no unique ID</a></li>
    </ul>
<li id="menuItem2" onclick="showMenu(this)"><a href="#">menuItem2</a>
    <ul>
    <li><a href='#'>submenu2, no uniwue ID</a></li>
    <li onclick="showMenu(this)"><a href='#'>submenu2, no unique ID</a>
  *      <ul>
        <li><a href='#'>submenu2-2nd column, no unique ID</li>
  *      </ul>
    <li><a href='#'>submenu2, no unique ID</a></li>
    </ul>
</ul>
</nav>

Another approach is to use a function that runs after the page loads to apply addeventlistener to each li tag instead of using the onclick attribute.

<body onload="load();"> 

Here is the corresponding function:

function load(){ 
    var lis = document.getElementsByTagName("li"); 
    for (var i = 0; i < lis.length; i++) {
        lis[i].addEventListener("click", function(){
            showMenu(this);
        }); 
    }
}

Keep in mind that not all browsers support the addEventListener function. In cases where Internet Explorer is being used, you may need to use attachEvent instead. Libraries like jQuery handle these differences seamlessly for developers, making it easier to use them instead of pure JavaScript in many cases.

Answer №2

How to Select the First Immediate Child Element?

After some trial and error, I discovered that changing [i] to [0] solved my problem. It's amazing how asking the right question can make all the difference!

By adjusting my code to target only the elements I need, I was able to streamline my array-loop process. Now, I'm exploring ways to apply this solution to all submenus without relying on unique IDs.

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

What is the best way to connect the state of a variable from one class to another in React?

How can I utilize the variable "restaurants" in Editar2.js? ---App.js--- const { restaurantes } = this.state; ---Editar2.js--- const ChooseRestaurant = (props) => { const options = props.restaurants.map((option) => { return(<opt ...

Transferring JavaScript to PHP

I have a challenge where I need to pass a string stored in a variable to a MySQL table using PHP. Currently, my workaround involves using a hidden <input>. I assign the variable value to it and submit it through a form. It works, but it's not e ...

Maximizing React Performance: Strategies for Avoiding Unnecessary Renderings on State Updates

I am facing a major performance issue due to constant re-rendering of my child components on every state change. I need a solution to prevent this from happening and maintain the stability of my application. Any suggestions or guidance would be highly ap ...

I am attempting to arrange 9 images in a grid format of 3 rows by 3 columns to create a seamless

I am currently working on setting up a 3x3 grid on my website with 9 images and text underneath. The first 6 images are displaying as I intended, but when I add the last 3 images, the layout gets messed up. The first image jumps under the 3rd image on the ...

Efficiently handling jsonwebtoken errors in node and express

Here is the verification function I've created: exports.verifyToken = function(req, res, next){ var token = req.body.token; jwt.verify(token, config.sessionSecret, function(err, decoded) { if(err){ return next(err); }else{ ...

Verifying the status of a checkbox label in Java using Selenium

I am currently working on an automation project using Selenium and I'm struggling to figure out how to check the status of a checkbox input. Has anyone else encountered this issue before? Here is a sample code snippet in JavaScript with jQuery: $("i ...

Elements resize based on their parent's and siblings' widths

I have organized the parent div and its three children divs. Presently, the third child is concealed. I've designated the width of the first child as 20% and desire for the second child to automatically take up the remaining width without explicit set ...

Creating new form fields dynamically using JavaScript (triggered by onClick event)

I want to dynamically add fields based on user interaction. For instance, when the checkbox or radio button is clicked, additional fields like buttons and textfields should appear. Is it possible to achieve this using onClick? If so, can you please provide ...

A guide to retrieving JSON data with Javascript

I'm in the process of building a small website for weather forecasting. However, I've encountered an issue when trying to retrieve JSON data from accuWeather - I'm not getting any response. I've double-checked my request and it seems to ...

Fancybox overlay not adjusting to full height

When working with JavaScript: $(document).ready(function() { $(".fancybox").fancybox({ helpers: { overlay: { opacity: 0.4, css: { 'background-color': '#FFF' ...

Adjust picture dimensions when the window changes (using jQuery)

Hey there, I'm in need of some help resizing images on my webpage. I want the images to adjust their size when the page loads or when the browser is resized. The images can be either portrait or landscape, and they will be contained within a div that ...

Guide to retrieving a string value rather than Json output with a mongodb aggregate function

I have a function that retrieves the value of the 'minHospitalization' field from the database. The response from this function is '[{"minHospitalization":1}]' Instead of returning the value in JSON format, I want to return just ' ...

Using React JS to iterate over an array and generate a new div for every 3 items

It's a bit challenging for me to articulate my goal effectively. I have a JSON payload that looks like this: { "user": { "id": 4, "username": "3nematix2", "profile_pic": &qu ...

invoke the modal function from a separate React file

I am currently studying react and nextjs. I am experimenting with calling a modal from another file but unfortunately it's not functioning as expected. Here is the code I used: Signin.js import { Modal } from "react-bootstrap"; import { u ...

Is it possible to showcase a notification as a popup or alert in Django?

I'm working on a form in Django that redirects to itself after submission. I want to show a message saying "You have entered (work_area)" as a popup or alert that users can close. However, my current setup only displays the message within the HTML aft ...

What could be causing my CSS to not display properly on GitHub Pages?

Currently working on a web-based game project called Sweet Shoppe, and utilizing GitHub Pages for hosting. However, encountered an issue where the CSS does not seem to be functioning properly on GitHub Pages. Attempted placing the CSS file in the main rep ...

Customizing the appearance of ASP.NET file uploader for various sizes

Has anyone successfully changed the width of the ASP.NET file uploader? I attempted by adding the CssClass, but it did not work. Is there an alternative method to adjust the width? Thanks in advance. ...

Utilize JSON categories to assign groups to TextFields or Selects according to a JSON data attribute

I have retrieved multiple JSON groups from an API, each containing one or more questions objects. My goal is to display each question along with its corresponding response in a MUI TextField or Select component, based on the value of QuestionType. Current ...

How can I use Angular to dynamically open a video that corresponds to a clicked image?

I need assistance with a functionality where clicking on an image opens a corresponding video on the next page. The issue is that all images have the same ID, making it difficult to link each image to its respective video. Below is the data I am working ...

Create a new column in Material UI Grid by adding an empty div element instead of using padding

I'm currently getting acquainted with Material UI Grid and I am interested in adding an empty column (a blank space on the right of the first element) without utilizing padding. How can this be achieved? Here's a snippet of the code being discus ...