How can I change the class of an element using javascript?

  • 0
    & lt; li & gt; has a class: class = "havesubchild sub mpIt mpId2" . It needs to be changed to class = "mpIt mpId21" . How can I do this using javascript?
    JavaScript Brielle Ho, Jan 5, 2020

  • 3 Answers
  • 0
    document.querySelectorAll('.havesubchild').forEach((el) => {
    el.classList.remove('havesubchild')
    })

    document.querySelectorAll('.havesubchild').forEach((el) => {
    el.classList.add("mpIt", "mpId21")
    })
    Anonymous

  • 0
    If one tag is:



    document.querySelector('.havesubchild').classList.remove('havesubchild', 'sub')




    If a lot:



    document.querySelectorAll('.havesubchild').forEach((el) => {
    el.classList.remove('havesubchild', 'sub')
    })
    Emma Goodman

  • 0
    Based on your knowledge, use jQuery. Here is the link, there is the code, just use minimal effort and substitute your values: https: //api.jquery .com / toggleClass / # toggleClass-cl ... . And don't forget to include the jQuery library to your site.
    Aden Berg

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!