skip to Main Content

I am calling a method that accepts a value, and that value then determines whether or not the classList is added or removed.

In the code below, if you pass "add" to the test method, it should add the classList, and if you pass "remove" it should remove it.

This code below doesn’t work.

test (val) {
    const fileName = document.querySelector('.file-name')
    const fileSize = document.querySelector('.file-size')
    const updatedAt = document.querySelector('.uploaded-at')

    fileName.classList.val('line-through', 'text-gray-400')
    fileSize.classList.val('line-through', 'text-gray-400')
    updatedAt.classList.val('line-through', 'text-gray-400')
}

ex) test(‘remove’) should remove the classList and test(‘add’) should add it

2

Answers


  1. You can use bracket notation to access a property of an object evaluated as a result of an expression. In your particular case:

    fileName.classList[val]('line-through', 'text-gray-400')
    fileSize.classList[val]('line-through', 'text-gray-400')
    updatedAt.classList[val]('line-through', 'text-gray-400')
    
    Login or Signup to reply.
  2. Use the toggle() method, which accepts a boolean as an optional argument to specify whether to add or remove the class.

    filename.classList.toggle('line-through', val == "add");
    filename.classList.toggle('text-gray-400', val == "add");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search