我总是使用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/