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

`Javascript often returns NaN for basic calculations`

Hello, I am currently developing a basic calculator for a game but I have encountered an issue. Despite having just started learning this programming language and reading all available tutorials, I am now in the process of writing code to gain more experie ...

Tips for displaying real-time data and potentially selecting alternative options from the dropdown menu

Is there a way to display the currently selected option from a dropdown list, and then have the rest of the options appear when the list is expanded? Currently, my dropdown list only shows the available elements that I can choose from. HTML: < ...

Redirecting to new page after submitting form using Ajax

I'm having some trouble with my HTML form submission using JQuery and AJAX. After successfully submitting the form, I want to display a modal and then redirect to another page based on certain conditions. I've written the logic in my JS file wh ...

Identifying a failed Ajax Request in JavaScript

How can I check if an Ajax request failed to load a file? Here is the code I'm currently using: var pro = undefined; var xmlhttp; if (window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); } else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTT ...

What is the best way to modify the size of a canvas element while maintaining effectiveness?

I've encountered an issue while using Canvas to create a pie chart with chart.js. Despite adjusting the dimensions of the canvas element, it continues to take up the entire page. <canvas id="myChart" height ="200" width="200"></can ...

Convert your AS3 code to JavaScript with our specialized compilers

Recently, I came across the AS3 to JS compiler known as Jangaroo. It caught my attention because it seems like a valuable tool that aligns well with my preferences in AS3. Are there any similar compilers out there? Is there another programming language ...

What is the correct way to iterate through a list of images fetched with getStaticProps and display them within the same component?

What is the proper way to map a list of images returned using getStaticProps? I had successfully implemented this by passing a prop to the gallery component in another page. However, I now want to consolidate all the getStaticProps code within the gallery ...

Issue with UseState causing a re-render not to be triggered

My orders list state works perfectly on the initial update. However, when an order in the database gets updated, the order list is updated but fails to trigger a re-render even with <...> const [orders, setOrders] = useState([]); useEffect(( ...

Can you explain the significance of "=>" in a context other than function invocation?

Working my way through the freeCodeCamp JavaScript course has left me quite puzzled about arrow functions. I know how to write a function using arrow notation, like this: const myFunc = () => "value"; However, in one of the later challenges, ...

What is the best way to use AJAX to load a PHP file as a part

I'm exploring different methods for making an AJAX call with an included file. Let's create a simple working example. Initially, I have my main index.php file which contains the following content. In this file, I aim to access all the data retur ...

Converting Strings into Variable Names in Vue.js: A Step-by-Step Guide

Hi everyone, I was wondering if there's a way to convert a string into a variable name. For example, I want to convert "minXLabel" to minXLabel so that I can use it within span tags like this: <span>{{minXLabel}</span>. I current ...

The issue I'm facing is that the ng-click functionality in Angular JS is not functioning properly when the

Upon loading the page, my JavaScript function creates a tree structure from JSON data and generates a list of anchor tags which look like this: <a ng-click="shareParent(4619)">Some data</a> Despite associating the ng-click directive with the ...

Tips for telling the difference between typescript Index signatures and JavaScript computed property names

ngOnChanges(changes: {[paramName: string]: SimpleChange}): void { console.log('Any modifications involved', changes); } I'm scratching my head over the purpose of 'changes: {[propName: string]: SimpleChange}'. Can someone cl ...

Why is my JavaScript code running but disappearing right away?

I've encountered an issue with the code I wrote below. It's supposed to display the user's names when they enter their name, but for some reason, the names keep appearing and disappearing immediately. What could be causing this problem? Her ...

Tips for validating forms using jQuery

Upon form submission, an alert is displayed before redirecting to a new page. I have implemented a function that triggers on button click. The alert will appear first, followed by the form submission. I would appreciate ideas on how to validate the form. ...

Redis appears to be missing the expected results

After following an express demo which involved storing and retrieving values with Redis, I attempted to implement the code in my own Express app. However, I encountered issues as the req.online variable was returning null when I tried to retrieve its lengt ...

The log indicates that there are two distinct IP addresses associated with the user

I find that this question may be better suited for another Stack Exchange board, and I am open to migrating it there if needed. In the development of a web application, we record certain event information to assist in diagnosing any potential issues. One ...

The order of items in MongoDB can be maintained when using the $in operator by integrating Async

It's common knowledge that using {$in: {_id: []}} in MongoDB doesn't maintain order. To address this issue, I am considering utilizing Async.js. Let's consider an example: const ids = [3,1,2]; // Initial ids retrieved from aggregation con ...

Using ReactJS and react-router to exclude the navigation menu on the login page

I have a LoginPage designed like this: After logging in, you will be directed to this page: Now, I want the login page to have no navigation and look like this: How can I achieve that? In my App.js, I have the following code: import React, { Component ...

Instructions on utilizing the signUp() function in Supabase for including extra user details during the registration process

My latest project involves building a Vue.js application with authentication using Supabase. I've been trying to implement the signUp() method from Supabase in order to collect extra user data during the sign-up process. In my code, I added a property ...