What is preventing me from toggling classes?

Managing a compact to-do list where you have the ability to add new tasks and when clicking on an item, it should toggle between two classes while removing one.

<ul id="myUL" class="todoList">
    <li class='todoList card border-primary'>my li</li>
</ul>

This snippet shows the JavaScript code responsible for toggling classes:

$( "#myUL" ).children().on("click",function() {  
    $( this ).toggleClass( "checked" );
    $( this ).toggleClass( "border-primary" );
    $( this ).toggleClass( "border-success" );                                                                              
});

The script is included after bootstrap.min and jquery-3.3.1.min files as they are dependencies for Bootstrap components.

However, there seems to be an issue with the code only functioning on the first element. How can this be resolved?

Answer №1

This JavaScript code will only apply to the first element because it attaches eventlisteners just once. To make it work for multiple elements, you can add a listener to the parent and handle events from there. Another option is to remove all eventlisteners from each list item and then re-add them with the current code, although this is not considered best practice.

// Add a "checked" symbol when clicking on a list item
var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
  if (ev.target.tagName === 'LI') {
    ev.target.classList.toggle('checked');
  }
}, false);

Source: https://www.w3schools.com/howto/howto_js_todolist.asp

Answer №2

Why don't you give this approach a shot?

$("#myUL li").click(function() {  
                   $(this).toggleClass("checked");
                   $(this).toggleClass("border-primary");
                   $(this).toggleClass("border-success");

  });

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

Troubleshooting Unresolved Issues with MongoDB and Node.js Promises

In my node.js code, I have utilized MongoDB to retrieve certain numbers. Below is the snippet of my code: MongoClient.connect('mongodb://localhost:27017/mongomart', function(err, db) { assert.equal(null, err); var numItems = db.col ...

Tips for resolving the cross-origin resource sharing (CORS) origin error in Jquery when encountering issues with the

Hi Team, I am encountering an error that I cannot resolve. My post method consistently fails when making a REST client request using Visual Studio Code or any other RESTful tool, not just in the browser. jquery.js:9664 POST ->url<- 404 (Not Found) ...

Is there a way to modify the badge class color in Bootstrap 4 using CSS?

The badge class in Bootstrap v4.3.1 is defined as follows: .badge { display: inline-block; padding: 0.25em 0.4em; font-size: 75%; font-weight: 700; line-height: 1; text-align: center; white-space: nowrap; vertical-align: baseline; ...

What is the best approach for utilizing AJAX to load content into a Lightbox based on the user's selected trigger?

Developing a custom Lightbox/Thickbox gallery program involves sending user-clicked data to load the appropriate content in the lightbox feature. Below are the important files used in this creation: show-hide-lightbox.js - Contains an Ajax request that ...

Tips for personalizing the NavigatorIOS's right side

Looking to create a navigation bar similar to Whatsapp's? I want to include a profile picture and call button on the right side of the bar. Any tips on how to achieve this look? Which properties should be used for this customization? Would it be bet ...

What steps can be taken to troubleshoot an AJAX error that does not display any error messages?

Within my ajax code, I have the following: $(document).ready(function(){ $("form input#dodaj").click(function(){ var s = $("form input#zad").val(); var str = "<li>"+s+"</li>"; $.ajax( { type: "GET", ...

What is the process for inserting text into a Word document using the Google Docs API?

Struggling to generate a Word document with text and images, but the text refuses to show up. My document remains blank, even though there seems to be no issue with my code. Any guidance on what I might be missing would be greatly appreciated. gapi.client ...

Retrieve the Response object when an ASP.NET Button is clicked

Within my ASP.NET Webform, I have a server-side Button with an Onclick event registered on it. <asp:Button ID="UploadButton" CssClass="btn add btn-primary" runat="server" Text="Upload File" OnClick="UploadBut ...

Optimal approach for customizing the appearance of child components based on the parent component

I'm curious about the optimal method for styling child components based on their parent component. For instance, I want to design a list component that can be utilized in both a dropdown popup and a toolbar, each with its own unique style. There are ...

Using JavaScript to open a document file in Chrome at launch

Is it possible to automatically open a doc file stored on my C:// drive when a link is clicked on my HTML page? Here is the code I have been using: <a href="C://mytestfile.doc">Click Me To launch the DOC FILE</a> Unfortunately, instead of op ...

Managing error responses while fetching a blob through AJAX

Is it possible to execute an AJAX call that has the potential to return either a blob or a text string based on the server's response? My current task involves using AJAX to transform a user-provided video into an audio blob that can be utilized with ...

Troubleshooting a jQuery filter function selector issue

Here's a function I've created: $.fn.filterByClass = function(cls) { var o = $(this); return o.filter(function() { if ($(this).attr("class") == cls) { return $(this); } }); }; Let's say we have multiple fo ...

Obtain the unique identifiers for each element within an array and attach them to the option values for each item

Forgive me for any misuse of terms, as I am relatively new to Javascript. However, I hope I can describe the desired result effectively in order to receive assistance with my inquiry. Within the code snippet below, there is an array named dates that outpu ...

Enhance your Facebook sharing by including unique element IDs as hashes in PHP code

Over at this specific page, I have a collection of neatly presented mp3 files in stylish boxes. Each one of these boxes features a Facebook share button. I'm looking to incorporate the unique identifier for each box, such as (mp3jWrap_0, mp3jWrap_1, ...

Margins are added to cards on the right side

Looking for some help to improve the display of three cards in a grid. The card media has a max-width of 345px, but this is causing excessive margin-right space and making the styling look poorly. Any suggestions on how to eliminate this extra margin? If ...

Transform a protractor screenshot into a PDF file

I'm currently working on a small Protractor code that captures screenshots, but my goal is to save these screenshots as PDF files. Below you can find the code snippet I have written. await browser.get(url); const img = await browser.takeScreenshot(); ...

Can the value of ng-model be altered without using ng-change function?

Can the ng-model value be altered without using the ng-change function? The method below does not seem to work. <div ng-app="myApp"> <div ng-controller="MyCtrl"> <input id="checkbox" type="checkbox" ng-model="field"> <div> {{field ...

Error: JSON data couldn't be processed due to an unexpected end, resulting in a SyntaxError at JSON.parse()

I'm currently working on making an ajax call to an API, but I keep encountering an error whenever I try to make the call. I've been troubleshooting this for hours and I can't seem to figure out what the issue is. At one point, I even removed ...

What is the best way to modify a current state object without causing an endless loop of redirects?

const useCase = (argument) => { const [value, setValue] React.useState(argument) React.useEffect(() => setValue({...value ...argument), [argument, value, setValue]) } The above code is currently causing an infinite loop due to setting the stat ...

What is the best way to position two out of the three link tags to the right side?

This is the code snippet I am currently working with: <table> <tr> <td>&nbsp;</td> <td> <a id="btnAutoSuggest">Suggest Title</a> <a id="btnOK">OK</a> <a id ...