Tips for utilizing JavaScript getElementByClassName to retrieve all the elements within a ul without having to specify the class name in each li

Looking to tidy up my HTML/CSS. Is there a way to keep this JavaScript functioning without needing to add the class name to every li element within the ul? Any suggestions on how to improve the visual appeal and readability of the HTML code?

const ProfileForm = document.getElementsByClassName('profile_container');
const dash = document.getElementsByClassName('dashboard_buttons');
var index;
var array = [];
for (var i = 0; i < dash.length; i++) {

  array.push(dash[i]);

  dash[i].onclick = function() {
    index = array.indexOf(this);

    ProfileForm[index].style.display = "block";

    var check = ProfileForm[index];

    for (var i = 0; i < ProfileForm.length; i++) {
      if (ProfileForm[i].style.display == "block" && ProfileForm[i] != check) {
        ProfileForm[i].style.display = "none";
      }
    }
  }

}
<ul>
  <li class="dashboard_buttons"><i class="far fa-user"></i>Profile</li>
  <li class="dashboard_buttons"><i class="far fa-list-alt"></i>My Properties</li>
  <li class="dashboard_buttons"><i class="far fa-money-bill-alt"></i>My Offers</li>
  <li class="dashboard_buttons"><i class="fas fa-file-contract"></i>My Utilities & Ejari</li>
  <li class="dashboard_buttons"><i class="far fa-heart"></i>Favourite Properties</li>
  <li class="dashboard_buttons"><i class="far fa-envelope"></i>Messages</li>
  <li class="dashboard_buttons"><i class="fas fa-cogs"></i>Settings</li>
</ul>

Answer â„–1

For selecting li elements within a specific ul, you can use the following code:

document.querySelectorAll("ul#myList li")
. This allows you to target only the li elements within the ul with the ID of "myList". Remember, using
document.querySelectorAll("ul li")
will select all li elements in the entire document.

<ul id="myList"><li>...</li></ul>

document.querySelectorAll("ul#myList li")

Answer â„–2

If you want to efficiently handle all events within a parent element, consider using event delegation. By utilizing event listeners over inline event handlers, you can achieve this while maintaining a clean separation between HTML and JavaScript.

To provide a simple demonstration, the code snippet below showcases how to unhighlight all list items and then highlight the clicked one. Please refer to the comments within the code for a more detailed explanation.

Does this example help clarify how you can accomplish your desired functionality?

// When the `ul` element is clicked, call `highlightItem` function
const list = document.getElementsByClassName("list")[0];
list.addEventListener("click", highlightItem);

// Define the event listener function
function highlightItem(event){ // The listener has access to the triggering event

  const clickedElement = event.target; // Utilize the event's `target` property

  // Check if the click occurred on an `li` element
  if(clickedElement.tagName.toLowerCase() == "li"){

    // Select all list items
    const items = list.querySelectorAll("li");

    // Iterate through the collection
    for(let item of items){

      // Update the classList of the current item in the loop
      item.classList.remove("highlight");

      // Add or remove class based on whether it was the target of the click event
      if(item == event.target){ item.classList.add("highlight"); }
    }
  }
}
.highlight{ background-color: yellow; }
<ul class="list">
  <li>Profile</li>
  <li>My Properties</li>
  <li>My Offers</li>
</ul>

Answer â„–3

One approach is to utilize query selector method

// Retrieve all 'li' tags throughout the page that have a class of "example"

let elements = document.querySelectorAll("li.example");

Answer â„–4

Try replacing document.getElementByClassName with document.querySelectorAll

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

Leveraging the CSS-Element-Queries Library for emulating the functionality of CSS media queries

Recently, I used a nifty CSS-Element-Queries tool to perform basic element manipulations that trigger whenever the window is resized. In simple terms, my goal was to dynamically adjust an element's attribute based on the current width of the window â ...

Implement a hover animation for the "sign up" button using React

How can I add an on hover animation to the "sign up" button? I've been looking everywhere for a solution but haven't found anything yet. <div onClick={() => toggleRegister("login")}>Sign In</div> ...

Effortless login authentication using Disqus through Google or Facebook tokens

I have set up my website to allow users to authenticate through Google and Facebook using passport, which uses the OAuth 2.0 API. Additionally, I am utilizing Disqus to manage the comments system on my site. However, I am running into a problem where user ...

Initiate an AJAX call and in the event that a particular object is found in the JSON response, proceed to send a subsequent request targeting

My objective is to make an AJAX request to a URL and expect a JSON response consisting of two objects: group_id and next_page. If the next_page object is set, I want to send another AJAX request using the value of next_page as the URL. If there is no next_ ...

Navigate to a specific hidden div that is initially invisible

Currently, I am working on a web chat application using next.js. The app includes an emoji picker button, which, when clicked, displays a menu of emojis. However, the issue I am facing is that the user has to scroll down in order to see the emoji menu. I a ...

I'm facing an issue with SSRProvider in my NextJs application

My application is developed using NextJs and Typescript, utilizing the react-bootstrap library for creating components. I am facing an issue where I keep receiving an error message stating that When server rendering, you must wrap your application in an &l ...

I am attempting to adjust the color of the active tab, but I seem to be encountering issues in my code. Can anyone help me

The currently active tab should change along with the text inside the box, but it's not working as expected. I'm struggling to find out why. Here is a fiddle to demonstrate my progress so far: var btn1 = document.getElementById("btn1"); va ...

The data from the Subscribe API call is gradually loading within the ngOnInit() function

When using Angular 8, I am experiencing slow data retrieval when making API calls in the ngOnInit() function. The issue arises when trying to pass this data as @Input from one component module to another - it initially comes through as undefined for a minu ...

"Troubleshooting a problem with Mongoose's findOne.populate method

There is an array of user IDs stored in the currentUser.follow property. Each user has posts with a referenceId from the PostSchema. I am trying to populate each user's posts and store them in an array called userArray. However, due to a scope issue, ...

Tactics for postponing a js function post-click

I need to implement a delay after clicking a button to fetch some data. The code will be executed within the browser console. $(pages()) is used to retrieve the pagination buttons. let calls = []; for (let i = 1; i <= callPagesCount; i++) { ...

Challenges with dropdown menus in the sub navigation area

I am currently working on a navigation system that includes three levels of sub-navigation elements. While the functionality is fine up to the third level, it only displays one subcategory instead of multiple categories as intended. I suspect there might ...

Chatting with a Discord bot

I am currently working on a Discord bot that will execute specific functions based on the questions asked, most of which are yes or no queries. Upon responding with "yes," a particular function should be performed, while answering "no" would terminate t ...

Deactivated dropdown menu options with the help of Twitter's bootstrap framework

Using markup, I have created a dropdown menu utilizing Twitter Bootstrap. <ul class="nav pull-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Menu <b class="caret"></b>< ...

The initial render of children elements in React Google Maps Api may not display properly

I am struggling to incorporate the Google Maps API into my app. Everything works smoothly until I try to display a Marker at the initial rendering of the map. The Marker does not show up, but if I add another Marker after the rendering is complete, then it ...

Utilizing PHP and AJAX to Extract Information from a MySQL Database

My goal is to fetch data from a MySQL database hosted on a webserver and display it in an HTML table. I've been following an example on W3Schools, but I'm facing issues retrieving the data successfully. Here is the source code: (HTML) <html& ...

Hapi/Node.js Reference Error for Request: Troubleshooting the Issue

I am facing an issue with my two API handlers: module.exports.loginWeb = function (request, reply, next) { if (request.auth.isAuthenticated) { return reply.redirect('/'); } if(request.method === 'get'){ rep ...

Retrieve the parent object from the policy field type

Imagine you have a query that retrieves a list of products like the one below. query ProductList() { products() { name price stockQuantity isAvailable @client # This field exists only locally } } In addition, you've set up a type ...

How can I pass an argument to Node within a package.json script instead of the script itself?

In my project's package.json, I have a script that looks like this: "scripts": { "test": "... && mocha --full-trace test/db test/http test/storage test/utils", I am trying to pass the --async-stack-traces o ...

How to Manage Empty Lines in HTML Documents within WordPress

Just recently, I launched my brand new website. Everything seems to be functioning properly except for one issue that I discovered in the HTML source code. There are 15 blank lines before "<!doctype html>", which is causing some problems with SEO and ...

Animated smooth updates in d3 line graphs are the key to creating dynamic and

I'm attempting to modify an example of Animated Line Graphs from: http://bl.ocks.org/benjchristensen/1148374 <div id="graph1" class="aGraph" style="width:600px; height:60px;"></div> <script> function draw(id, width, height, upd ...