你可能知道,獲取和設置 DOM 元素內部文本能夠用這兩個屬性:Node.textContent
和 Element.innerText
。css
乍一看,它們彷佛作着徹底相同的事情,但它們之間有一些微妙但重要的區別。今天,咱們來看看它們的做用,以及它們的異同之處。code
廢話不說,直接看代碼。class
好比下面這個 DOM 元素。渲染
<p id="sandwich">I love a good tuna sandwich!</p>
Node.textContent
和Element.innerText
屬性都能獲取#sandwich
元素內部的文本。im
let sandwich = document.querySelector('#sandwich'); // returns "I love a good tuna sandwich!" let text1 = sandwich.textContent; // also returns "I love a good tuna sandwich!" let text2 = sandwich.innerText;
若是元素內部還有其餘標籤,它們都會忽略。img
<p id="sandwich">I love a good <strong>tuna</strong> sandwich!</p>
// returns "I love a good tuna sandwich!" let textHTML1 = sandwich.textContent; // also returns "I love a good tuna sandwich!" let textHTML2 = sandwich.innerText;
另外,這兩個屬性都能用於設置元素內部文本。di
// 替換文本 // <p id="sandwich">Hello, world!</p> sandwich.textContent = 'Hello, world!'; // 也能夠追加 // <p id="sandwich">Hello, world! And hi, Universe!</p> sandwich.innerText += ' And hi, Universe!';
看上去作着一樣的事情,那麼它們有什麼區別?鍵盤
Node.textContent
屬性獲取所有文本內容,包括元素內部那些未渲染到頁面的內容。Element.innerText
只返回渲染出來的文本,相似於能夠用光標和鍵盤選中的文本部分。舉個例子就清楚了。loading
<div class="greeting"> <style type="text/css"> p { color: rebeccapurple; } </style> <p hidden>This is not rendered.</p> <p>Hello world!</p> </div>
let greeting = document.querySelector('.greeting'); /* 返回 p {color: rebeccapurple;} This is not rendered. Hello world! */ let text1 = greeting.textContent; // 返回 "Hello world!" let text2 = greeting.innerText;
這下總算知道區別了!又躺學了一個知識點~query
本文首發於公衆號 1024譯站