Skip to content

[Javscript] insertAdjacentHTML、insertAdjacentText,vanilla.js 就支援的插入 HTML 及文字

Published: at 08:45 AM

最近才知道 HTML 元素有 insertAdjacentHTML  insertAdjacentText這兩個方法,讓插入 HTML 或文字位置時可以比較有彈性。(類似 jQuery prepend 或 append 等等)

以下就來介紹他的用法吧~


insertAdjacentHTML(position, text) 及 insertAdjacentText(position, text)

position:

text: 期望插入的 HTML 字串或純文字。

ps. insertAdjacentTextinsertAdjacentHTML 差別就在 insertAdjacentHTML 僅允許插入純文字。

直接來看看程式碼或許會更理解囉~

參考資料:

https://developer.mozilla.org/zh-TW/docs/Web/API/Element/insertAdjacentHTML

https://developer.mozilla.org/zh-TW/docs/Web/API/Element/insertAdjacentText