常用的DOM操作方法有哪些? - 举例详解

5 min read

DOM常用的操作方法有以下几种:

  1. 节点访问方法(node access methods):可以通过getElementById、getElementsByClassName、getElementsByTagName等方法获取HTML元素节点,也可以通过parentNode、childNodes、previousSibling、nextSibling、nodeValue等属性访问节点之间的关系结构。

  2. 属性操作方法(attribute manipulation methods):可以使用getAttribute、setAttribute、removeAttribute方法访问HTML元素的属性,例如id、class、src等。

  3. 样式操作方法(style manipulation methods):可以使用style属性或者getComputedStyle方法获取元素的样式,也可以使用classList属性对元素的类名进行添加、删除或者替换操作。

  4. 创建、修改、删除节点方法(create, modify, delete node methods):可以使用createElement、createTextNode、appendChild、insertBefore、replaceChild、removeChild等方法对DOM中的节点进行增删改操作,例如添加新元素、删减不需要的元素、更改元素内容等。

  5. 事件处理方法(event handling methods):可以使用addEventListener、removeEventListener等方法处理DOM中的事件,例如点击事件、鼠标移动事件、键盘按键事件等。