Acquire the <li> element when it is clicked using vanilla JavaScript

Whenever a user enters a value in an input field, my function automatically adds a <li> element to a <ul>. Additionally, the function assigns the attribute ( onclick="doneToggle" ) to the created <li>.

function createListElement() {
    var li = document.createElement("li");
    ul.appendChild(li);
    li.appendChild(document.createTextNode(input.value));
    li.setAttribute("onclick", "doneToggle()")
    li.setAttribute("style", "width: fit-content")
    input.value = "";
}

The doneToggle function is designed to add a specific CSS class to the clicked element, giving the text a "line-through" style.

Here is the existing function:

function doneToggle(element) {
    element.classList.toggle("done");
}

I wish for this function to toggle the class of the clicked element without the need to assign IDs to the <li> elements. Your assistance is greatly appreciated.

Answer №1

It is recommended to use

Element.prototype.addEventListener()
rather than using the onclick attribute. By doing so, the event will be automatically passed to the handler function, allowing access to the event.target element on which the event occurred.

Instead of setting the onclick attribute like this:

li.setAttribute("onclick", "doneToggle()")

You should use addEventListener method as shown below:

li.addEventListener('click', doneToggle)

Then within the doneToggle function, you can work with the event passed and access the clicked element using event.target:

function doneToggle(event) {
    event.target.classList.toggle("done");
}

Answer №2

When working with event listeners, the keyword this is used to reference the element that triggered the event. Instead of mistakenly using element, which actually refers to an Event Object, it's important to use this:

function doneToggle(event) {
    this.classList.toggle("done");
}

Rather than making changes directly to the "onclick" attribute, it's better to incorporate an event listener:

function createListElement() {
    var li = document.createElement("li");
    ul.appendChild(li);
    li.appendChild(document.createTextNode(input.value));
    li.addEventListener("click", doneToggle)
    li.setAttribute("style", "width: fit-content")
    input.value = "";
}

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

Web Page Content Scrambling/Character Exchange

I've encountered a perplexing issue that seems to strike randomly, yet I've managed to replicate the problem on three different desktops. Oddly enough, some other desktops never experience this issue and I'm at a loss as to what could be cau ...

Designing Object-Oriented JavaScript

Currently, I am in the process of developing a sophisticated JavaScript application. Utilizing an object-oriented design approach, I have organized my code into various files to enhance maintainability. In order to create my application, what is the best ...

JavaScript's ability to call object properties at multiple levels allows for complex data

My approach involves using mongodb in conjunction with ajax calls for data retrieval. However, I have encountered an issue where the properties needed to generate HTML from JavaScript objects are sometimes missing. Consider this ajax call: $.ajax({ ...

Inspect the json data to find a specific value and then determine the corresponding key associated with

I am currently working with JSON data retrieved from which I am storing in a variable. Despite my limited experience with JSON/JS, I have been unable to find a solution through online searches. Here is the code snippet: function checkMojang() { var moj ...

Angular: Exploring the differences between $rootScope variable and event handling

I have a dilemma with an app that handles user logins. As is common in many apps, I need to alter the header once the user logs in. The main file (index.html) utilizes ng-include to incorporate the header.html I've come across two potential solution ...

If the item already exists within the array, I aim to replace the existing object with the new one

I am faced with a situation where I have an array of objects, and when a user selects an option, it adds a new object to the array. My goal is to write a code that can check if this new object's key already exists in one of the objects within the arra ...

Improving the quality of shadows in Three.js

I'm looking to create realistic shadows in my scene using a DirectionalLight to simulate sunlight. However, I'm struggling with the shadow quality settings - toggling between on/off, Low, Normal, and High: Setting parameters a and b within these ...

Differentiating Typescript will discard attributes that do not adhere to an Interface

Currently, I am working with an API controller that requires a body parameter as shown below: insertUser(@Body() user: IUser) {} The problem I'm facing is that I can submit an object that includes additional properties not specified in the IUser int ...

emulating the behavior of a synchronous XmlHttpRequest

While I have taken the time to explore similar questions like Pattern for wrapping an Asynchronous JavaScript function to make it synchronous & Make async event synchronous in JavaScript, I want to ensure that I consider all potential solutions. Is it ...

Is there a way to automatically fill up a second dropdown menu based on the user's selection from the first dropdown

Using jQuery or vanilla JavaScript, I am looking to dynamically populate a second dropdown based on the selection made in the first dropdown. The value chosen in the first dropdown will determine which options are displayed in the second dropdown. What is ...

comparing caching with jquery deferred against promise

Currently, I have implemented code using jQuery Deferred and ajax to fetch data from a remote API, store it in localStorage, and retrieve it from there. However, this code has a bug where it doesn't display the data properly the first time it runs (re ...

What are some tips for incorporating vue.js into a basic web application?

I've been trying to incorporate vue.js into my web application, but for some reason, it's not loading and the HTML is not firing in the browser. Please take a look at the code snippet below: <!DOCTYPE html> <html> < ...

Tips for incorporating JSON data into an HTML table

https://i.sstatic.net/WEdge.jpgIn an attempt to showcase JSON data in an HTML table, I want the schoolClassName value to be displayed as a header (th) and the first names of students belonging to that specific schoolClass to appear in a column beneath the ...

Unexpected results occur when accessing data in $uibModal.open() within Angular JS causing it to

Here is the code snippet that is causing the issue of returning undefined items in AngularJS: App.js code console.log('single page application script is working'); var myApp = angular.module("demoApp", ["ngRoute", 'ui.bootstrap',&apos ...

ContainerView: challenges encountered when dynamically inserting views

ContainerView.pushObject() does not automatically connect dynamically added views with a Container object. The absence of an auto-wired container leads to a rendering error when a view renders a template containing a handlebars render helper. SIMPLE SCENA ...

Steps to close a socket upon session expiration

I am currently working on a small express application that also incorporates a socket program. Everything works perfectly when a user successfully logs in - it creates the session and socket connection seamlessly. However, I encountered an issue where eve ...

Guide on exporting a reducer from a Node module built on React Redux

I am currently working on a project that requires importing a component from an external node module. Both the project and the component utilize React and Redux, and I intend for them to share the same store. Below is a snippet of the reducer code for the ...

The AJAX form fails to submit the information, causing PHP to not process the request

I encountered an issue with this particular form a few days ago which was resolved using a different PHP code provided by the helpful folks here. However, after making a small change to the form, it no longer works. I have verified that all the variables b ...

Guide to bringing in a variable from an external module

As a backend developer working on Node.JS code, I am trying to incorporate some constants from the @aws-sdk/signature-v4 module into my project. Specifically, I need to access AMZ_DATE_QUERY_PARAM as mentioned in the documentation. However, I am struggling ...

Setting limits to disable or remove specific times from the time picker input box in Angular

I'm having trouble with a time input box. <input type="time" min="09:00" max="18:00" \> Even though I have set the min and max attributes to values of 09:00 and 18:00 respectively, it doesn't seem to be working properly. I want to ...