How to only change the text in a DOM element without replacing any child elements

前端 未结 7 1249
一个人的身影
一个人的身影 2021-01-17 17:58

Hi I have a simple html structure

Title text inner text

What I want is to replace only the te

7条回答
  •  情歌与酒
    2021-01-17 18:23

    const ChgBtn = document.querySelector('#change-title')
    const title = document.querySelector('#page-title')
    
    ChgBtn.addEventListener('click', (event) => {
      if (title.innerHTML === 'job') {
        title.innerHTML = 'better job'
        event.target.innerHTML = 'Change title back'
      }
      else if (title.innerHTML === 'better job') {
        title.innerHTML = 'job'
        event.target.innerHTML = 'Change Title'
      }
      else {
        console.error('Wrong')
      }
    })
    

提交回复
热议问题