简体   繁体   中英

how to linethrough a text if checkbox is checked

I am trying to make a to-do list with a checkbox for each element. When the checkbox is checked I want my element to be styled line-through.

Here is my code

I have this HTML

<h1>My List</h1>
<input id="item" type="text" />
<button id="add">Add</button>
<ul id="toDo"></ul>

and js

document.addEventListener('DOMContentLoaded', function () {
    const addButton = document.querySelector('#addButton');

    addButton.addEventListener('click', function () {
        const textInput = document.querySelector('#itemText');
        const itemText  = textInput.value;

        if (itemText) {
            const ul = document.querySelector('ul');
            const li = document.createElement('li');

            li.addEventListener('click', function (e) {
              if (e.target!=checkbox){
                e.target.parentNode.removeChild(e.target);
              }

              //i try do use this
              if (e.target==checkbox){
              if (checkbox.checked == true){
               e.target.parentNode.textContent.style.textDecoration = "linethrough";

               } 
              }


            });


          var checkbox = document.createElement('input');
          checkbox.type = "checkbox";
          checkbox.value = 0;

          li.appendChild(checkbox);
          li.appendChild(document.createTextNode(itemText));

           ul.appendChild(li);
           textInput.value = '';
        }
    });
});

I get Uncaught TypeError: Cannot set property 'textDecoration' of undefined. How to style the text next to the checkbox I clicked?

e.target.parentNode.textContent is pure string so you cannot use style and textDecoration in this case.

Also use "line-through" instead "linethrough"

So use the below one and will be fine!

e.target.parentNode.style.textDecoration = "line-through";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM