A method for adding a strikethrough to text within a list item upon clicking a button

Hi there! I'm just starting out with JS, HTML, and CSS and I could really use some help. I've been researching solutions but I'm struggling to apply them to my specific situation. I'm trying to add an onClick function to Button 2 and implement a strikethrough effect, but I'm not quite sure how to do it. Any guidance would be greatly appreciated!

This is the JavaScript code I have so far:

window.onload = function() {
    document.getElementById("submit-btn").addEventListener("click", function() {
            let text = document.getElementById("text-box").value;
            let li = document.createElement("li");
            li.id = "liId";
            li.innerText = text;
            document.getElementById("unordered-list").appendChild(li);
            
            let button = document.createElement("button");
            button.innerText = "X";
            button.setAttribute = ("id", "b1");
            li.appendChild(button);
            button.addEventListener("click", () => li.parentNode.removeChild(li));
            document.getElementById("unordered-list").appendChild(li);
            
            let button2 = document.createElement("button");
            button2.innerText = "Done";
            button2.id = "b2";
            li.appendChild(button2);
           
            li.appendChild(button);
            li.appendChild(button2);
    });
    document.getElementById("b2").addEventListener("click", function () {
    document.getElementById("liId").style = "text-decoration: line-through;"
});
}

And here's the HTML code:

<html lang="en">
    <head>
        <link rel="stylesheet" href="style.css" />
        <title>My First Project</title>
    </head>
    <body>
        <script src="script.js"></script>
        <header id="to-do-box">
            <h1>To-Do List</h1>
            <div id="top-half">
                <form>    
                <input type="text" id="text-box" placeholder="Add an item!">
                <button type="button" id="submit-btn">Submit</button>
                <button type="button" id="clear-field-btn">Clear field</button>
                </form> 
            </div>
        </header>
        <div id="ul">
            <ul id="unordered-list"></ul>
        </div>
   </body>
</html>

Answer №1

One way to achieve this is by adding an event listener that triggers when a button is clicked. This listener will remove the first displayed list item.

   document.getElementById("submit-btn").addEventListener("click", function() {
            let text = document.getElementById("text-box").value;
            let li = document.createElement("li");
            li.setAttribute = ("id", "list");
            li.id = "liId";
            li.innerText = text;
            document.getElementById("unordered-list").appendChild(li);
            
            let button = document.createElement("button");
            button.innerText = "X";
            button.setAttribute = ("id", "b1");
            li.appendChild(button);
            button.addEventListener("click", () => li.parentNode.removeChild(li));
            document.getElementById("unordered-list").appendChild(li);
            
            let button2 = document.createElement("button");
            button2.innerText = "Done";
            button2.id = "b2";
            button2.classList.add('buttonClass');
           
            
            li.appendChild(button2);

document.querySelectorAll('.buttonClass').forEach(item => {

             item.addEventListener('click', event => {
               change()
})})});


function change() {

      document.querySelectorAll("#b2").forEach(item => {
          item.parentNode.style = "text-decoration: line-through;"

})}

document.getElementById("clear-field-btn").addEventListener('click', event => {

document.querySelectorAll("#b2").forEach(item => {
          item.parentNode.remove();
})
})
               
<html>
<body>
<header id="to-do-box">
            <h1>To-Do List</h1>
            <div id="top-half">
                <form>    
                <input type="text" id="text-box" placeholder="Add an item!">
                <button type="button" id="submit-btn">Submit</button>
                <button type="button" id="clear-field-btn">Clear field</button>
                </form> 
            </div>
        </header>
        <div id="ul">
            <ul id="unordered-list"></ul>
        </div>
   </body>
</html>

It's important to note that this method only removes one of the list items. To remove all list elements if the user has multiple, you will need to use a forEach loop.

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

Is there a way to verify the content of a span and automatically guide the user elsewhere if it meets certain criteria?

Currently, I am facing an issue with adding Google authentication to my website as the redirect function is not working properly. As a solution, I plan to implement manual redirection using JavaScript in case the value of the span element is <span id= ...

Angular: A guide to binding to the required/ngRequired attribute

There is a directive that may or may not be required, and it can be used in two different ways. <my-foo required></my-foo> or <my-foo ng-required="data.value > 10"></my-foo> Even though require and ngRequire are essentially t ...

Utilize jQuery to serialize the HTML input elements that are dynamically generated outside of the form

A proof of concept is in progress for an application that involves the generation of HTML elements based on user-configured fields. Here is a sample configuration: // Customer SAM $response = array( array ( NAME => CUSTOMER, TYPE = ...

Guide on incorporating an external HTML file into an ASP.NET webpage

Is there a way to incorporate an external HTML file into a ASP.NET web page? In PHP, we typically use the include function for this purpose. I am looking for a similar solution in ASP.NET as well. My goal is to have a shared header HTML file that can be ...

Using React Native to Store Items in Flatlist via AsyncStorage

My challenge involves displaying/storing a list of items in a flatlist. The issue arises when I save an item and then load it on another screen; there seems to be a repetitive pattern (refer to the screenshot). Additionally, adding a new item results in re ...

Does Objective C have a counterpart to the encode() method in JavaScript?

NSString *searchString = @"Lyngbø"; NSLog("%@",[searchString stringByAddingPercentEscapeUsingEncoding:NSUTF8StringEncoding]); The result is: Lyng%C3%B8 <script type="text/javascript"> document.write(escape("Lyngbø")); </script> The result ...

customizing the appearance of a plugin

Visit the live site here. I am attempting to customize the text displayed in black under the Upcoming Events section. Despite multiple attempts using different combinations such as .vevent-item odd event-1 .description .event-time .event-label, I have not ...

Is your webpage slow to respond after a page-refresh? (Delayed HTML rendering causing lag)

Whenever I adjust the screen size to that of a phone or any device smaller than 768px, the search bar doesn't display in its proper position until the page is refreshed. It should be correctly placed right from the start. Furthermore, when I resize th ...

Having trouble with submitting the AJAX form when trying to rate something

Need help with the review rating code. The form submission does not save data to the database. Any assistance is appreciated. <form id="commentform" method="POST" action="#" class="form form-inline form-contact"> <p class="push-down-20"> ...

Issue with Ajax: parameters failing to pass without using jQuery

It appears that I am only receiving jQuery results, but I am in search of the correct method to pass parameters via AJAX without using libraries or old browser fallbacks. If there is another thread discussing this topic that I have overlooked, please provi ...

Trouble displaying portrait images in CSS slideshow

My portfolio includes an image slider called wow slider, which can be found at You can view my site with the image slider on this page: http://jackmurdock.site50.net/StudioWork.hmtl While most of the galleries display portrait and landscape images correc ...

Preventing users from selecting past dates in HTML input date field

I need help with disabling past dates in an HTML date input field. Even though I am able to restrict selecting past dates on the date picker, I can still save data if I manually type in a previous date (e.g., 12/08/2020). $(document).ready(function() { ...

Ways of transferring session variables from one page to another?

Initially, I am working with multiple webpages in express. After saving a variable into a session during a post request, the page redirects to another page. However, when trying to access the variable on that new page, it is returned as "Undefined." Upon f ...

Internet Explorer is failing to render SVG as content within a pseudo element such as :before or :after

Looking to tackle an issue that stems from the following discussion: Is there a way to use SVG as content in a pseudo element :before or :after. I'm attempting to add a svg triangle after a div using a pseudo-class. div{ background-color: black; w ...

The columns in the table are hidden when resizing

There are three tables in my code. The first table does not have any margin set, while the next two tables have a margin-left property to slightly move them to the left side. However, when I resize the window, I'm unable to see the last column in the ...

Incorporating a self-invoking anonymous function to enhance Sir Trevor within an AngularJS framework while also making use of

I recently started working with AngularJS and I have an App where I am using the Sir Trevor content editor. I want to add some custom blocks to the editor by extending it, but I am having trouble accessing angular services within my extension code. The ext ...

Retrieve the text content of the paragraph element when its parent is clicked. The paragraph element belongs to a group that contains many

In a function I'm working on, I need to retrieve the specific text within a p element when its parent (.photoBackground) is clicked. The purpose of this operation is to grab the caption for a gallery, where there are multiple p elements with the same ...

Is it possible to maintain a div's height in proportion to its width using CSS?

Is it possible to set a CSS variable so that my div's height is always half of its width, and the width scales with the screen size (in percentage)? <div class="ss"></div> CSS: .ss { width: 30%; height: 50% of the width; } This ...

When using jQuery Ajax, only pass the query string if it is defined and not empty

Using jquery and ajax to communicate with a CMS API, I am constructing a query string to fetch data: region = typeof region !== 'undefined' ? 'region='+region : ''; centre = typeof centre !== 'undefined' ? 'cen ...

Adding a border around the `<tr>` elements in a table

How can I add a border to the <tr> element (t_border), without the inner table inheriting the style from the outer one? <table> <tr> <td>A</td> </tr> <tr> <td> <ta ...