DOM 有哪些常见操作?
参考答案
查询
querySelector/querySelectorAll、getElementById、getElementsByClassName/TagName、closest、matches
创建与插入
createElement、createTextNode、createDocumentFragment、append/appendChild/insertBefore、insertAdjacentHTML/Element、replaceWith、cloneNode
修改
textContent、innerHTML、setAttribute/getAttribute/removeAttribute、classList.add/remove/toggle、style.xxx、dataset
删除
remove()、removeChild、replaceChildren
遍历
parentNode、children、firstChild/lastChild、nextElementSibling、childNodes
尺寸与位置
getBoundingClientRect、offsetWidth/clientWidth/scrollWidth、scrollTop
事件
addEventListener/removeEventListener、dispatchEvent
要点:批量操作先离屏(DocumentFragment / 断开再插回)以减少重排;避免频繁读写混排(布局抖动)。