Tips for Isolating a Single Element Within a Parent Container

I'm currently working on a basic to-do list feature where, upon checking the checkbox next to an item, both the text and delete button get a strikethrough style. Is there a way for me to apply the strikethrough effect only to the text element, leaving the delete button unaffected?

Although I attempted to target specific children elements in my code, as a novice coder, I might have made mistakes along the way. I'm struggling to identify how to isolate the text item exclusively without impacting the delete button.

Code Snippet

let taskList = document.getElementById('taskList');
let taskBox = document.getElementById('taskBox');
let taskCount = 0;

document.addEventListener('keypress', function(e) {
  if (e.key === 'Enter') {
    addTask();
  }
});

function addTask() {
  let taskVal = taskBox.value;

  if (taskVal.length < 1) {
    window.alert('Task Box Empty');
  } else {
    let itemDiv = document.createElement('li');
    let itemCheck = document.createElement('input');
    let textItem = document.createTextNode(taskVal);
    let itemDelete = document.createElement('button');

    itemDiv.classList.add('itemDiv');

    itemCheck.style.height = "50px";

    itemCheck.type = "checkbox";
    itemCheck.name = "finished";
    itemCheck.id = "checkbox";

    textItem.innerText = taskVal;
    itemDelete.innerText = "x"

    taskList.append(itemDiv);
    itemDiv.appendChild(itemCheck);
    itemDiv.appendChild(textItem);
    itemDiv.appendChild(itemDelete);
    taskCount++;

    itemCheck.onclick = finishTask.bind(itemCheck);
    itemDelete.onclick = deleteItem.bind(itemDiv);
    document.getElementById('taskBox').innerHTML = "";

    taskBox.value = "";
  }
}

function finishTask() {
  let children = this.parentNode.children;
  if (this.checked) {
    this.parentNode.style.textDecoration = "line-through";
  } else {
    this.parentNode.style.textDecoration = "none";
  }
}
<h1>My To-Do List</h1>
<hr>
<div class="addTaskContainer">
  <input id="taskBox" type="textarea" placeholder="Add Task" autocomplete="off">
  <button class="add" onClick="addTask()">Add Task</button>
</div>

<ul class="taskList" id="taskList"></ul>

<button class="bottomBtn" onClick="clearAll()">Clear All</button>

<button class="bottomBtn" onClick="clearFinished(itemCheck)">Clear Finished</button>

Answer №1

To make your text more visually appealing, consider wrapping it in a span element.

Start by deleting this particular line:

let textItem = document.createTextNode(taskVal);

Instead of the removed line above, use the following code snippet to create a span element:

let textItem = document.createElement('span');
textItem.innerText = taskVal;

Next, ensure you select and modify the span within its parent node with the function below:

function finishTask() {
  let textNode = this.parentNode.querySelector('span')
  if (this.checked) {
    textNode.style.textDecoration = 'line-through';
  } else {
    textNode.style.textDecoration = 'none';
  }

  // Alternatively
//   let textNode = this.parentNode.querySelector('span')
//   textNode.style.textDecoration = this.checked ? 'line-through' : 'none';

}

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

The Ajax call was successful but the callback function failed to return

I've been encountering some challenges with a small application I'm developing. After successfully setting it up to automatically populate one field with the same value entered in another field, I decided to integrate an AJAX request into the scr ...

Combine strings in an array of objects

I have an array containing objects with a "Closed" property that holds numerical values. I want to loop through the array and concatenate all the "Closed" property values found in each object. For example, in the given array, the final result should be 12 ...

Is it possible to retrieve a variable from code.gs and pass it to my html file?

I had originally set up an automated email system to trigger once a certain condition was met, which I successfully implemented. However, I now want to enhance the email by including a more structured format and embedding an image from Google Drive. While ...

Navigate to the subsequent field in an HTML5 form without any manual intervention

I have created the following HTML5 form: <form> <input type="text" name="orderno" /> <input name="picture" id="img" type="file" accept="image/*" capture="camera" /> <input class="btn-success" type="submit" name="submit" value="Uplo ...

Choose the dropdown item depending on the related text

I am currently working on a drop-down menu where each option has a value and associated text. The selected option is then displayed row by row in a table, with an edit button next to each row that allows the user to change the selection. I am trying to imp ...

Updating the rotation of a grandchild in Three.js Object3D

In my current project, I am attempting to make the grandchild of a rotated Object3D element face towards the camera using the lookAt() method. I have experimented with various approaches to achieve this. However, the source code for the Object3D.lookAt() ...

Sharing a document that contains a linked image file using a relative path through the `publish` feature

I have reviewed the documentation and tested the steps provided in this example, but I am still unable to find a solution for the issue at hand. Based on the documentation, the image file should either be located in the same path as the MATLAB script bein ...

Does the Sass default compiler have built-in autoprefixing capabilities?

Suppose I have the following sample code: :fullscreen a { display: flex; } Is it possible for the default sass compiler to transform it into this: :-webkit-full-screen a { display: -webkit-box; display: flex; } :-moz-full-screen a { display: fle ...

Modify css with php instead of using FTP

As I work on constructing a website, I wonder how WordPress allows its admin users to edit CSS styles through the website instead of accessing the css file directly via FTP. How exactly does WordPress load the CSS file? My assumption is that it somehow re ...

Using Angular 2 to execute an interface while making an HTTP GET request

I've managed to successfully retrieve and display data from a JSON object using *ngFor in Angular. However, I am struggling with applying an interface to the retrieved data. This is the content of my interface file: import {Offer} from './offer ...

Trouble with setting the color attribute using setProperty in a GXT text area

Help needed in dynamically changing the font color of a text area from the color menu. Existing attempts to change it have not been successful. Can someone provide assistance? final ColorMenu fontColorMenu = new ColorMenu(); fontColorMenu.getPalette().a ...

Guide on sending emails with AngularJS and the Ionic framework

I have been attempting to send an email by using various links, but without success. I am looking for guidance on how to successfully send an email. Below is the code I have been using for sending emails. Any suggestions for changes would be greatly apprec ...

Refresh cloned element after making changes to the original element

Just starting to explore Jquery and looking for some guidance to get me started :) Question: I'm facing an issue with a cart total price that is displayed in a different part of the page using clone(). I want this cloned price to automatically update ...

What is the best way to deactivate div elements once an overlay has been applied to them?

My goal is to place an overlay on my form to prevent users from accessing the content. Even though I have added an overlay, users can still interact with input fields. How can I prevent that? .overlay { background: rgba(0, 0, 0, .75); text-align: ce ...

Verify if a selection of days using momentjs exceeds 7 days

Is there a way to determine if more than 7 days have been selected on the calendar? I need to disable a button based on this condition. fromDate and toDate are global variables where I store dates from the calendar. Feeling a little confused at the moment ...

Adding a header to a UL list: making it stand out at the top!

I have two UL's: How can I insert text into the top green area. The text must not be within an LI element. Despite several attempts, the text keeps appearing outside the boxes. I have tried wrapping the two UL's in both a div and a span (curre ...

Preventing responsive elements from loading with HTML scripts

Currently, I am utilizing the Gumby framework which can be found here. Everything appears to be running smoothly. My goal is to incorporate a mobile navigation list where the links are grouped under a single button, as outlined here. Initially, this funct ...

Designing Tables for User Interfaces

In a table with 4 rows, the first row must always be filled by the user. The remaining rows are optional. What is the best way to visually indicate this requirement? This should be achieved using only HTML, CSS, and jQuery. ...

Guide on integrating a RESTful API within a router using the Express framework

I am trying to fetch data from the following link: using express.js. I have developed a Single Page Application website using react.js for the frontend, so I need to make a call to this route : /shipping/check/cost in my backend to retrieve the required ...

What exactly is the significance of localizing an Aria label?

Looking to add an aria label that needs to be localized. What exactly does this mean? Here is the code I have: <a href="link"><i class="button" aria-label="back button"> How do I modify this code in order to make ...