Adding an id to a ul tag using JavaScript

I am trying to dynamically add an ID called "myMenu" using JavaScript to a ul element for a search filter. Unfortunately, I am unable to directly access the ul tag to change it, so I need to do it via JavaScript. As I am new to JavaScript, I am looking to switch from targeting elements by class to specifically target the ul element.

<div class="main-menu">
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</div>

<input type="text" id="mySearch" onkeyup="myFunction()" placeholder="Search.." title="Type in a category">
function myFunction() {
  // Declare variables
  var input, filter, ul, li;
  input = document.getElementById("mySearch");
  filter = input.value.toUpperCase();
  ul = document.getElementById("myMenu");
  li = ul.getElementsByTagName("li");

  // Loop through all list items, and hide those who don't match the search query
  for (let i = 0; i < li.length; i++) {
    if (li[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}

Answer №1

If you're looking to include an identifier to the ul displayed in your example, simply follow these steps:

$("div.main-menu ul").attr("id", "myMenu");

According to @Rory-MacCrossan, do you actually require an id for this?

Answer №2

If you want to achieve this with vanilla JavaScript, you can use the following code snippet:

const ulEl = document.querySelector('.main-menu > ul');
ulEl.setAttribute('id', 'main-menu-list');

console.dir(ulEl);
<div class="main-menu">
  <ul>
    <li></li>
    <li></li>
    <li></li>
  </ul>
</div>

It might be more suitable to change <div class='main-menu'> to <div id='main-menu'>, unless there are other elements that should have the main-menu class.

You can refer to these resources for more information:

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute

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 CSS to automatically adjust the width of a child div based on its content, rather than stretching it to fill the entire

I'm currently facing an issue with my CSS. Apologies for the vague title, but I'll do my best to explain it here. My problem lies within a parent wrapper div that is centered on the page. Within this wrapper, there is another child div containing ...

Utilizing Pagination in Python Django to Handle URL Identifiers

I'm encountering a small issue with the following code: Html Code : a href="{% url 'entertainment:novelsView' novel.id %}">buttonclass="pull-right btn btn-primary btn-xs">Link span class="fa fa-link"</span></button</a vi ...

Is there a way to prevent the letters from moving when I hover over them?

What occurs when the numbers are hovered over: https://gyazo.com/20b6426d435551c5ee238241d3f96b4d Whenever I hover over the pagination numbers, they shift to the right, and I am unsure of what mistake I made in my code that's causing this. Below, I ...

Tips on utilizing useStyle with ReactJS Material UI?

Is there a way to utilize a custom CSS file in the useStyle function of Material UI? I have created a separate useStyle file and would like to incorporate its styles. Can someone explain how this can be accomplished? input[type="checkbox"], inp ...

Ways to display a checked or unchecked checkbox in react depending on a boolean value obtained from an API

Is there a way to display a checked or unchecked checkbox in react jsx depending on a boolean value retrieved from an api? ...

What is the best way to merge angularjs modules?

In my angularjs application using the codeigniter PHP framework, I have implemented 3 modules - cars.js for car details, cellphones.js for cellphone details, and home.js for home details. Each module caters to a different client's needs. I am trying ...

Submitting data to an external PHP file using the JavaScript function $.post

Having issues with the PHP page function ajaxFunction(){ var ajaxRequest; try{ ajaxRequest = new XMLHttpRequest(); } catch (e){ try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequ ...

Retrieve JSON object by matching another JSON property

I am working with an array of id's and their respective contents in a JSON response. My goal is to retrieve the content based on the received id. For instance, if the ID is 1 (returned from the JSON), I aim to access the JSON data using "data.id" (wh ...

When switching between classes, it is not possible to apply a different value to the same CSS property

I am currently working on a project that involves toggling a class on a ul tag with an id of sideNav using JavaScript. In this scenario, I have set the left attribute of the id to 0, while the same attribute in the class has a value of -100%. After sever ...

Using Jquery for conditional statements: if versus else

$("#bottomWatch").click(function(){ var doops = $(".videoMove").display; if (doops == "none") { $("#video").css("left","15%", "display: block"); } else { $(".videoMove").cs ...

A guide on displaying data in a table using a select dropdown in a pug file and passing it to another pug file

After creating a single page featuring a select dropdown containing various book titles from a JSON file, I encountered an issue. Upon selecting a book and clicking submit (similar to this image), the intention was for it to redirect to another page named ...

Importing components in real-time to generate static sites

My website has a dynamic page structure with each page having its unique content using various components. During the build process, I am statically pre-rendering the pages using Next.js' static site generation. To manage component population, I have ...

Clearing AsyncStorage in React Native

It has come to my attention that I am spending a significant amount of time debugging redux actions in react-native that are being persisted to AsyncStorage using redux-persist. There are instances where I wish I could simply clear AsyncStorage in order to ...

Assistance needed for iterating through JSON data

I need assistance retrieving specific data from a JSON response in my JavaScript code. Unfortunately, the current approach is not providing the desired results: This is my JavaScript code snippet: function retrieveArtists(response){ var artistList ...

Scraping the web using Python for HTML data retrieval

I'm working on a Python program to retrieve the card sub-brand and brand based on a card BIN number. The URL for this information is: . The code snippet below fetches the card type from the page. page = requests.get('https://www.cardbinist.com/s ...

Is there a way to modify the CSS of the sequential number element when it is clicked on?

I've successfully utilized jQuery to create sequential numbering for my menu items. Upon clicking, the hyperlink text changes color to red. However, I'm facing an issue where I want the corresponding number to also change to red when the hyperli ...

Customize the CSS for a Material UI popover styling

I am currently working with a Material UI popover and attempting to apply CSS styles to it. This is the code for my popover component: import React, { memo, useCallback } from 'react'; import PropTypes from 'prop-types'; import { ...

Tips for distinguishing between the different values

Greetings! I am currently utilizing this code snippet to retrieve values from a Java class. Upon getting the data from Java, it triggers an alert displaying two values separated by spaces. My next goal is to split the values into two separate entities an ...

Is there a way to initiate the server only after webpack has finished bundling all of the bundles

"scripts": { "start": "node server.js", "build": "webpack" }, Is there a way to execute both npm run build and npm start with a single command? "scripts": { "start": " ...

Get around operator precedence in JavaScript

Imagine having a string like this: '1 + 2 + 3 * 4' Can you solve it sequentially from left to right in order to obtain a total of 24, instead of 15? It's important to note that the string is unknown beforehand, so it could be as simple as ...