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

Issue with the iOS gyroscope detected when rotating specifically around the z-axis

I am facing a unique challenge with an unusual bug and I'm looking for help from anyone who has encountered this issue before or can provide a solution. My current project involves using Javascript to access the gyro on iOS devices, specifically focu ...

Guide to building a JavaScript array and storing data from a separate array into the newly created array in JavaScript

Can you help me create a JavaScript array and save another array of data to be part of the newly created array in JavaScript? I attempted it using the code below. Code: var vvv=this.new_products.length-this.quote.lines.length; let mmm={}; if(v ...

Nodejs restricts the user from performing the action

Currently, I am utilizing Nodejs with Expressjs and encountering an issue when trying to run the project. The connection is established successfully but when attempting to access the URL (localhost:3001/api/plans), an error appears in the console: MongoSer ...

What is the best way to display and conceal various elements with each individual click?

Utilizing the onClick function for each triggering element, I have implemented a show/hide feature for multiple element IDs upon click. The default setting is to hide the show/hide elements using CSS display property, except for the initial 3 main elements ...

Blank YouTube Popup Modal

I am in the process of creating a pop-up modal that contains an embedded YouTube video, but my modal is not displaying properly. I am utilizing Bootstrap and have two separate sections along with JavaScript code. When the modal appears, it remains empty. I ...

Is there a way to modify Style Properties in JavaScript by targeting elements with a specific class name using document.getElementsByClassName("Class_Name")?

I am seeking a solution to change the background color of multiple div boxes with the class name "flex-items" using JavaScript. Below is my current code: function changeColor(){ document.getElementsByClassName("flex-items").style.backgroundColor = "bl ...

Filters in VueJs do not produce any results

Example of Basic Code <!DOCTYPE html> <html> <head> <title>My First Vue Application</title> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b9cfcc ...

Track the loading time of a webpage and the time it takes to render all subelements of

For my project, I need to track page load times for each individual visitor. My idea is to embed a JavaScript snippet into the page in order to achieve this goal. However, the task is more complex than I anticipated because I also need to measure the respo ...

Challenges with asynchronous problems related to importing models utilizing promises in conjunction with the three.js

I'm currently struggling to resolve a promise in my script. The promise needs to be resolved when a function containing 3D file imports finishes importing, but I'm unsure how to make this happen. Is there a way to receive a signal or data from t ...

Upon installation, the extension that replaces the new tab fails to detect the index.html file

edit: Check out the Chrome Extension here Edit 2: It seems that the recent update containing the index.html file was not published due to Google putting it under revision. Apologies for forgetting to include the index.html file in the upload zip, as I ...

Jade not responding to AngularJS click directive function

This tutorial is inspired by the MEAN Stack demo: Mongo, Express, AngularJS, and NodeJS I am attempting to incorporate a 'delete' method into my controller in the Jade template as shown below: characters.jade script function CharactersCont ...

Trouble retrieving data (React-redux)

Greetings! I am currently working on a project involving the Spotify API and attempting to retrieve new releases. While the data is successfully passed down to the reducer, I encounter an issue when calling the fetch action in my App component. When I try ...

Should tabs be closed or redirected after successful authentication with Google?

I have a project that was developed using perl-dancer and angular. The project is integrated with Google as an openID system. On some of the pages, there is an edit grid with a save button. To prevent loss of unsaved data when the session (created from pe ...

AngularJS ng-click incompatibility causing non-functioning popover content

I've gone through all the posts regarding this issue, but unfortunately, none of them proved to be helpful. It seems that the jsfiddle and plunker links provided are no longer functioning as expected. My objective is quite simple - I want to place a ...

sophisticated method for sorting through data within an array of arrays

How can data be filtered from an array of arrays? Below is an example to help explain the process. To filter the data, use startnumber and endnumber in the query. const data = [ { "name": "x", "points": [ [100, 50, 1], //[number, value ...

Exploring ElectronJs: The journey to sending messages from ipcMain to IpcRender and awaiting a response

I need help with sending a message to ask the renderer to parse an HTML string mainWindow.webContents.send('parse html', { resp}) The renderer processes the data and sends a reply ipc.on('parse html',function(e,p){ let b ...

Saving the output of mySQL queries on the client side for later use in subsequent requests

While logging a user in, I transfer attributes through a response object. In the javascript, I store specific attributes to a variable for future usage. For example, onresponse - currentUser = req.body.user currentID = req.body.id etc. Later, if I need t ...

Received an unexpected GET request while attempting to modify an HTML attribute

After clicking a button in my HTML file, a function is called from a separate file. Here is the code for that function: function getRandomVideoLink(){ //AJAX request to /random-video console.log("ajax request"); var xhttp = new XMLHttpRequest( ...

How can I stop VSC from automatically inserting "require"?

Every time I edit certain JS files in VSC, it automatically inserts "require()" calls that I then have to delete. Is there a way to stop VSC from adding these lines with "require"? Appreciate any help, Didier ...

Running a script within an Ajax-rendered form using remote functionality in a Ruby on Rails

After clicking the following button, my form is rendered: = link_to 'New Note', new_note_path, :class => "btn btn-primary new-note-button", :type => "button", :id => "new-link", remote: true The form is rendered using the script below ...