javascript - 将 html(text) 附加到元素而不影响同级元素?

标签 javascript dom

我总是使用appendChild向其他元素添加一些内容,因为如果我使用:

innerHTML +=  'added stringgggggggggg';

那么这会弄乱动态元素,例如 <form> ,填充值(它将字段值重置为空)。

有没有更短的方法可以将 smth 添加到元素,而无需 appenChild并且不使用 JQuery?

最佳答案

您可以使用element.insertAdjacentHTML()评估原始 HTML 字符串并将其附加到元素。

element.insertAdjacentHTML('beforeend', '<p>put me inside at the end</p>');

通过更改 position 属性,您可以在元素之前、之后、开头或结尾处插入。

<!-- beforebegin -->
<p>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</p>
<!-- afterend -->

innerHTML 不同,insertAdjacentHTML() 不会导致浏览器重新评估您要注入(inject)的整个 DOM 节点,因此请形成字段值将予以维护。

var parentEl = document.getElementById('parent');
parentEl.insertAdjacentHTML('beforeend', '<p>this paragraph was inserted at the end of the form without affecting the form field values!<p>');
<form id="parent">
  <input type="text" value="insert something after form"><br>
  <input type="text" value="without affecting the values"><br>
  <input type="text" value="in the form fields"><br>
</form>

关于javascript - 将 html(text) 附加到元素而不影响同级元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38945032/

相关文章:

javascript - AWS Lambda postgres 连接超时,但仅在第一次尝试时

jquery - 如何使用 jquery 查找元素的第 n 个父元素

php - HTML DOM : how to properly use the textContent property with PHP

javascript - 每个中的 jQuery 变量范围

c# - 如何在不同的浏览器中获取 Html 文档,当 Html 文档完全加载时作为图像?

javascript - insertRow 与 appendChild

PHP DOM 和 JavaScript 以及 HTML 实体

javascript - 标签更换前的 polymer 纸标签(卸载前)

javascript - 选择具有相同操作的不同js文件

javascript - 如何合并排序的数字列表中的连续数字?