banner
 Sayyiku

Sayyiku

Chaos is a ladder
telegram
twitter

常用 DOM 方法比較

innerText 對比 textContent#

總結如下:

  • innerText 獲取的文字的換行符依然保留;
  • innerText 無法獲取隱藏文字;
  • innerText 性能要相對差一些;

由於 innerText 存在諸多特別的特性、以及兼容性差異,以及性能方面問題,以及實際開發的需求的考量,不推薦使用,推薦使用 textContent 獲取文本內容

var text = dom.textContent

如果你的專案還需要兼容 IE8 瀏覽器,則使用下面的代碼:

var text = dom.textContent || dom.innerText

注:vue 的 v-text 指令就是更新元素的 textContent

getAttribute 對比 dataset 對象#

例如,有如下 HTML:

<button id="button" data-author="zhangxinxu">作者是誰?</button>

使用 getAttribute 和 dataset 對象都能獲取 data-author 屬性值:

button.getAttribute('data-author') // zhangxinxu
button.dataset.author // zhangxinxu

差別在於大小寫敏感的區別,getAttribute 方法是無視大小寫的,而 dataset 對象必需要使用小寫,例如:

<button id="button" data-AUTHOR="zhangxinxu">作者是誰?</button>
button.getAttribute('DATA-author') // zhangxinxu
button.dataset.AUTHOR // undefined
button.dataset.author // zhangxinxu

如果自定義屬性包含多個詞組,則 dataset 對象屬性值需要使用駝峰命名獲取

<button id="button" data-article-author="zhangxinxu">感謝閱讀!</button>
button.getAttribute('data-article-author') // zhangxinxu
button.dataset.articleAuthor // zhangxinxu

getElementById 對比 querySelector#

一般情況下這兩個方法是等效的,但推薦使用 getElementById() 方法,因為這個 API 的容錯性最強,不容易導致 JS 運行中斷。

假設某個元素的 ID 是未知的,通過參數傳過來的,但是這個字符串參數可能各種各樣,假設這個字符串是 'thanksForShare!',此時分別運行下面的代碼:

document.getElementById('thanksForShare!') // 正常運行
document.querySelector('#thanksForShare!') // 報錯

結果 getElementById() 方法安全地返回了 null,但是 querySelector() 方法直接報錯了:

VM309:1 Uncaught DOMException: Failed to execute ‘querySelector’ on ‘Document’: ‘#thanksForShare!’ is not a valid selector.

也就是說,在使用 querySelector() 方法的時候,我們需要對裡面的選擇器進行合法性校驗,或者 try…catch 處理,否則就會影響整個 JavaScript 代碼的運行。因此優先使用 getElementById() 方法去獲取 DOM 元素

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。