10

知道这两个 DOM 属性区别的,头发应该不多了吧?

 3 years ago
source link: http://developer.51cto.com/art/202102/645169.htm
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

你可能知道,获取和设置 DOM 元素内部文本可以用这两个属性:Node.textContent 和 Element.innerText。

乍一看,它们似乎做着完全相同的事情,但它们之间有一些微妙但重要的区别。今天,我们来看看它们的作用,以及它们的异同之处。

废话不说,直接看代码。

相同之处

比如下面这个 DOM 元素。

I love a good tuna sandwich!

Node.textContent 和Element.innerText属性都能获取#sandwich 元素内部的文本。

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;

如果元素内部还有其他标签,它们都会忽略。

I love a good tuna sandwich!

// returns "I love a good tuna sandwich!"

let textHTML1 = sandwich.textContent;

// also returns "I love a good tuna sandwich!"

let textHTML2 = sandwich.innerText;

另外,这两个属性都能用于设置元素内部文本。

// 替换文本

//

Hello, world!

sandwich.textContent = 'Hello, world!';

// 也可以追加

//

Hello, world! And hi, Universe!

sandwich.innerText += ' And hi, Universe!';

不同之处

看上去做着同样的事情,那么它们有什么区别?

Node.textContent 属性获取全部文本内容,包括元素内部那些未渲染到页面的内容。

Element.innerText 只返回渲染出来的文本,类似于可以用光标和键盘选中的文本部分。

举个例子就清楚了。

This is not rendered.

Hello world!

let greeting = document.querySelector('.greeting');

/* 返回

p {color: rebeccapurple;}

This is not rendered.

Hello world!

*/

let text1 = greeting.textContent;

// 返回 "Hello world!"

let text2 = greeting.innerText;

这下总算知道区别了!又躺学了一个知识点~


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK