appendChild,insertAdjacentHTML和innerHTML有什么区别 [英] What is the difference between appendChild, insertAdjacentHTML, and innerHTML

查看:76
本文介绍了appendChild,insertAdjacentHTML和innerHTML有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 appendChild insertAdjacentHTML innerHTML 之间有什么区别.

I want to know what the difference is between appendChild, insertAdjacentHTML, and innerHTML.

我认为它们的功能相似,但是我想在用法方面而不是在执行速度方面清楚地理解.

I think their functionality are similar but I want to understand clearly in term of usage and not the execution speed.

  1. 例如,我可以使用 innerHTML 将新标签或文本插入HTML的另一个标签中,但是它将替换该标签中的当前内容,而不是附加内容.
  2. 如果我想这样做(而不是替换),则需要使用 insertAdjacentHTML ,并且可以管理要在哪里插入新元素( beforebegin 之后 beforeend afterend )

  1. For example, I can use innerHTML to insert a new tag or text into another tag in HTML but it replaces the current content in that tag instead of appends.
  2. If I would like to do it that way (not replace) I need to use insertAdjacentHTML and I can manage where I want to insert a new element (beforebegin, afterbegin, beforeend, afterend)

最后一个是我要创建一个新标签(而不是在当前标签中插入)并将新标签插入HTML中,我需要使用 appendChild .

And the last if I want to create (not insertion in current tag) a new tag and insert it into HTML I need to use appendChild.


我理解正确吗?还是这三个之间有什么区别?


Am I understanding it correctly? Or are there any difference between those three?

推荐答案

  • element.innerHTML

    来自MDN:

    innerHTML设置或获取描述元素后代的HTML语法.

    innerHTML sets or gets the HTML syntax describing the element's descendants.

    在写入 innerHTML 时,它将覆盖源元素的内容.这意味着必须加载并重新解析HTML.这不是很有效,尤其是在使用内部循环时.

    when writing to innerHTML, it will overwrite the content of the source element. That means the HTML has to be loaded and re-parsed. This is not very efficient especially when using inside loops.

    node.appendChild

    来自MDN:

    将一个节点添加到指定父节点的子节点列表的末尾.如果该节点已经存在,则将其从当前父节点中删除,然后添加到新的父节点中.

    Adds a node to the end of the list of children of a specified parent node. If the node already exists it is removed from current parent node, then added to new parent node.

    所有浏览器都支持此方法,这是一种将节点,文本,数据等插入DOM的更简洁的方法.

    This method is supported by all browsers and is a much cleaner way of inserting nodes, text, data, etc. into the DOM.

    element.insertAdjacentHTML

    来自MDN:

    将指定的文本解析为HTML或XML,并将结果节点插入到DOM树中的指定位置. [...]

    所有浏览器也支持此方法.

    This method is also supported by all browsers.

    ....

    这篇关于appendChild,insertAdjacentHTML和innerHTML有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆