skip to Main Content

enter image description here
enter image description hereyour text
enter image description here

Tried to add a class pre-styled when the click action happened.

enter image description here

how to add the line-through style to the element clicked using JavaScript/JQuery?

2

Answers


  1. You can replace e.target with whatever element it is you’re trying to change. Also, if you don’t want to change the styling on repeated clicks, you can simply use addClass or removeClass

    $('#clickme').on('click', function(e){
    
        $(e.target).toggleClass('stuff');
    
    });
    
    Login or Signup to reply.
  2. If you prefer, here is a non-jQuery solution.

    Assuming the elements in question are <li> type elements (if they’re not, simply replace the 'li' selector with the one you need):

    // get all elements on which you would like to set 'click' event listeners
    const listItems = document.querySelectorAll('li');
    
    // add 'click' event listeners to your elements
    listItems.forEach((li) => {
        li.addEventListener('click', function() {
            if (li.classList.contains('myClass')) {
                li.classList.remove('check');
            }
            else {
                li.classList.add('check');
            }        
        })
    });
    

    Similarly, as mentioned before, if you only want to add the class and not remove it on subsequent clicks, simply replace the whole if else statement with li.classList.add('check');.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search