Easily iterate through the <li> elements using jQuery and append them to the <datalist> dynamically

My jQuery loop seems to be malfunctioning as it's not showing the values of my li elements. Instead, I'm seeing [object HTMLElement] in my input search bar.

<div id="sidebar-wrapper">
   <input type="text" list="searchList" class="search" size="20" placeholder="Search..." /> 
    <datalist id="searchList"> </datalist>

        <ul class="sidebar-nav" id="menu">

            <li>
                <a id="item1" href="#item1">item1 </a>
            </li>
            <li>
                <a id="item2" href="#item2">item2</a>
            </li>

        </ul>
    </div>
<br>

 $('.sidebar-nav li').each( function(index,item) {
        var option = $('<option value="'+item+'">');
        $('#searchList').append(option);
    });

https://i.stack.imgur.com/QUWmx.png

Answer №1

Within the item tags will be li dom elements, resulting in the display of object HTMLLIELEMENT

To extract the content of each li, utilize the jQuery text method and trim any excess whitespace.

 $('.sidebar-nav li').each(function(index, item) {
 console.log(item)
        var option = $('<option value="'+$(item).text().trim()+'">');
        $('#searchList').append(option);
    });

JSFIDDLE

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 could be causing the malfunction of this JavaScript dropdown select feature in Internet Explorer?

I created a website that requires users to input their location, including the city and state. The process involves two dropdown menus: - The first dropdown menu, labeled "state," loads all USA states as selectable options when the website is loaded. This ...

Selection Change Event for Dropdown Menu

Just starting to learn JavaScript and currently working with 3 select elements on a JSP page: <select id="railwayServiceList" name="railwayService_id" onchange="changeCompaniesCombo()"></select> <select id="companyList" name="company_i ...

ng-disable will only evaluate when the page is initially loaded

I am facing an issue with around 10 textboxes on a form page. The condition I have is as follows: Disable the textboxes if the logged in user does not have permission Disable the textbox if the user has permission, but there is already a value loaded fro ...

Confirm whether the Iterator type is the same as the AsyncIterator type

Is there a clever JavaScript technique to differentiate between Iterator and AsyncIterator without initiating the iteration process? I'm attempting to create a type checker like this: function isAsyncIterator<T>(i: Iterator<T> | AsyncIter ...

Button-click scrolling is our featured feature!

One interesting feature on my website is a button (within a div-element) located in the bottom-right corner. I am now looking to enhance this by adding a jQuery function that enables the user to scroll down the page incrementally simply by clicking and hol ...

Guide to concealing List elements from the Search Filter when the search input field is emptied

I am facing a challenge with an HTML list of items. Here is the structure: <ul id="fruits"> <li><a href="#">Mango</a></li> <li><a href="#">Apple</a></li> <li><a href="#">Grape</a>& ...

What could be causing a tooltip to remain visible even after a mouseleave event in a React application

My goal is to display a tooltip when the mouse enters an item, and hide it when the mouse leaves. I created a demo that works perfectly fine. Check out the working demo here The above code successfully shows the tooltip on hover and hides it on leave. I ...

If other options fail, Else If may not be a suitable choice

This is the process: switching from Issue: x==0||1 to x==0||x==1 etc. This code runs from an .html file <body> <div class="" id="pimg1"> </body><script> var x=new Date().getMonth(); if (x == 0||x == 5||x == 2){docu ...

Create a word filter that doesn't conceal the words

I have a code snippet that filters a JSON object based on name and title. I also have an array of specific words and I would like to modify the filter to highlight those words in the text without hiding them. $scope.arrayFilter=["bad,bill,mikle,awesome,mo ...

Angular login/signup modal/dialog component for seamless user authentication

Currently, I am working on adding a login/signin dialog to my app similar to the one used by Medium. After doing extensive research online, I have decided to use the $modal from angular ui-bootstrap for this. Can anyone please recommend a tutorial that wil ...

Extracting numbers using regular expressions can be tricky especially when dealing with mixed

Currently, I am attempting to create a javascript regex that can extract decimal numbers from a string containing a mix of characters. Here are some examples of the mixed strings: mixed string123,456,00indeed mixed string123,456.00indeed mixed string123,4 ...

When zooming out, Leaflet displays both tile layers

I'm currently working on integrating two tile layers along with a control for toggling between them. Below is the code snippet I am using: const layer1: L.TileLayer = L.tileLayer('http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png', { ...

Using jQuery to apply a class to pagination elements that have been dynamically loaded via

$(".paginate li").click(function(){ $(this).attr('class','current'); $("#ajax_results").load("test.php?page=" + $(this).attr('rel')).fadeIn(); }); This script is designed for pagination functionality. When a user ...

Exploring a new method for AJAX loading when handling large amounts of data into multiple div elements

As I continue my learning journey with html and jquery, I have been exploring ways to replicate monitoring systems (SCADA) into web-based systems. During this process, I discovered openseadragon as a MAP system similar to google maps that allows for overla ...

Utilizing the NestJS Reflector within a Custom Decorator: A Comprehensive Guide

I have implemented a solution where I use @SetMetaData('version', 'v2') to specify the version for an HTTP method in a controller. Additionally, I created a custom @Get() decorator that appends the version as a suffix to the controller ...

Activate a Dropdown Menu by Clicking in a React Application

I have a collapsible feature where you can click to expand or collapse a dropdown. Currently, the dropdown can only be clicked on where the radio button is located. I want the entire area to be clickable so that users can choose the dropdown by clicking an ...

ExpressJS exhibits unique behavior based on whether the API is requested with or without the specified PORT number

I have encountered an issue with my 2 flutter web apps. One of them is functioning flawlessly when I request the URL, but the other one only works when I include the port xxxxx:4000/nexus-vote. However, when I remove the port, I receive a status code of 20 ...

Having issues displaying the & symbol in HTML from backend data

I recently worked on a project using express handlebars, where I was fetching data from the YouTube API. However, the titles of the data contained special characters such as '# (the ' symbol) and & (the & symbol). When attempting to render the ...

Exploring the possibilities of custom layouts for specific routes within the pages directory in Next.js

I am interested in incorporating layout-based routing within my project's pages directory. I want to find a way to have a specific file, like the _app.tsx, that can only affect the files located inside a particular folder. This setup would operate si ...

Best practices for updating the token in an Angular 2/5 application - tips on how, where, and when to refresh

Currently I am utilizing the following technologies: Django REST Framework Angular 5 RxJS + OAuth2 Within all components paths except LoginComponent, I have an AuthGuard to verify the token data stored in localstorage of the browser. If valid data is ...