简体   繁体   中英

I want a paragraph to get the line through style whenever a checkbox is checked and vise versa

It doesn't work as expected

I managed to make it work in this way:

 <div class="noteContainer">
            <p class="title">Hello World</p>
            <p class="note">This is the hello world note!
                <i class="fa fa-pencil-square-o noteEdit" title="Edit" aria-hidden="true"></i>
                <input onclick="setLineThrough()" type="checkbox" name="done" class="cbDone">
            </p>
 </div>
let checkBoxes = document.getElementsByClassName("cbDone");
const setLineThrough = () => {
    for (let i = 0; i < checkBoxes.length; i++) {
        if (checkBoxes[i].checked) {
            checkBoxes[i].parentElement.style.textDecorationLine = "line-through";
        } else {
            checkBoxes[i].parentElement.style.textDecorationLine = "none";
        }
    }
};

It wasn't exactly what I wanted

But then the line through also goes through my icon and to the checkbox so I decided to get them out of the <p> and made some changes and I was expecting it to work since they were so similar but it just adds the line through but it does not remove the line through when the checkbox is unchecked !

<div class="noteContainer">
            <p class="title">Hello World</p>
            <p class="note">This is the hello world note!</p>
            <i class="fa fa-pencil-square-o noteEdit" title="Edit" aria-hidden="true"></i>
            <input onclick="setLineThrough()" type="checkbox" name="done" class="cbDone">
      </div>
let checkBoxes = document.getElementsByClassName("cbDone");
let notePara = document.getElementsByClassName("note");
const setLineThrough = () => {
    for (let i = 0; i < checkBoxes.length; i++) {
        if (checkBoxes[i].checked) {
            notePara[i].style.textDecorationLine = "line-through";
        } else {
            notePara[i].parentElement.style.textDecorationLine = "none";
        }
    }
};

What is wrong with my second iteration? I just can't find it. Also take note that there are some css in my code but I don't think it is needed here.

You just need to delete one instance of .parentElement from your JavaScript.

Your JavaScript will then look like this:

let checkBoxes = document.getElementsByClassName("cbDone");
let notePara = document.getElementsByClassName("note");
const setLineThrough = () => {
    for (let i = 0; i < checkBoxes.length; i++) {
        if (checkBoxes[i].checked) {
            notePara[i].style.textDecorationLine = "line-through";
        } else {
            notePara[i].style.textDecorationLine = "none";
        }
    }
};

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