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

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


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

position:

  • beforebegin: 插入在元素標籤前(外層)
  • afterbegin: 插入在元素標籤內的開頭
  • beforeend: 插入在元素標籤內的結尾
  • afterend: 插入在元素標籤後(外層)

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

Leave a Reply