Home > Software design >  Cannot edit css of a class with variable
Cannot edit css of a class with variable

Time:02-14

I am trying to get a line through the li that i added when i click the li(like a grocery list).

$('document').ready(() => {
            let id = 1;

            $('.knop').click(() => {
                let boodschap = $('.tekst').val();
                let newli = `<li id="boodschap${id}"> ${boodschap}</li>`;
                $(".result").append(`${newli}`);
                id  ;
            });

            $('ul').click(() => {
                let target = event.target.id;
                $(`${target}`).css({
                    "text-decoration": "line-through"
                });
                console.log(event.target.id);
            });
        });

I know the problem is in this part:

 $('ul').click(() => {
                let target = event.target.id;
                $(`${target}`).css({
                    "text-decoration": "line-through"
                });

I dont get a error in my console. so im stuck. but when i hard code the part where i put my ${target} it works. you cant use a variable in the css function? is there a way around this?

CodePudding user response:

I believe your issue is that you are missing the # from your ID selector. Just add it like this:

$('ul').click(() => {
  let target = event.target.id;
  $(`#${target}`).css({
    "text-decoration": "line-through"
  });
});

Or just forget about the string ID selection and just select the element already being passed, like this:

$('ul').click(() => {
  $(event.target).css({
    "text-decoration": "line-through"
  });
});

CodePudding user response:

I see you have target.val in your top example but the specified code just hs target.

Which one do you have in your code?

Also should it be target.val()?

can you console log your target and target.val() to make sure its equal to what you are hard coding?


                let target = event.target.id;
console.log("my target", target)
console.log("target val", target.val())
                $(`${target}`).css({
                    "text-decoration": "line-through"
                });```

CodePudding user response:

So you need to strikeout an <li> when it's clicked.

$('li').on('click', (evt)=>{
    let target = evt.target;
    $(target).css({'text-decoration': 'line-through'});
    console.log(evt.target.id);
}

The main problem with your code is that you store target <li>'s id, in a variable called target, rather than the target element itself. Misleading variable names can lead to confusion.

  • Related