javascript innerHTML adding instead of replacing

前端 未结 6 1519
名媛妹妹
名媛妹妹 2020-11-30 04:32

quick question, i know we can change the content of a

hello one
by using:

docum         


        
6条回答
  •  遥遥无期
    2020-11-30 05:20

    Notice that using element.innerHTML += 'content' would empty inputs and textareas to their default, blank state, unclick checkboxes, as well as removing any events attached to those elements (such as onclick, on hover etc.) because the whole innerHTML would be reinterpreted by the browser, which means .innerHTML is emptied and filled again from scratch with the combined content.

    If you need to keep the state, you'd need to create a new element (a for instance) and append it to the current element, as in:

    let newElement = 'span'
    newElement.innerHTML = 'new text'
    document.getElementById('oldElement').appendChild(newElement)
    

提交回复
热议问题