当前位置: 首页 > 科技观察

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

时间:2023-03-18 11:32:46 科技观察

p{color:rebeccapurple;}如您所知,您可以使用这两个属性来获取和设置DOM元素的内部文本:Node.textContent和Element.innerText。乍一看,它们似乎在做完全相同的事情,但它们之间存在一些细微但重要的区别。今天,我们来看看它们的作用,以及它们的相同点和不同点。废话不多说,直接看代码。下面的DOM元素也是如此。Iloveagoodtunasandwich!

Node.textContent和Element.innerText属性都可以获取#sandwich元素内的文本。letsandwich=document.querySelector('#sandwich');//返回“Iloveagoodtunasandwich!”lettext1=sandwich.textContent;//也返回“Iloveagoodtunassandwich!”lettext2=sandwich.innerText;如果元素内还有其他标签,它们将被忽略。Iloveagoodtunasandwich!

//返回“Iloveagoodtunasandwich!”lettextHTML1=sandwich.textContent;//也返回“Iloveagoodtunassandwich!”lettextHTML2=sandwich.innerText;这两个属性都可用于设置元素的内部文本。//替换文字//Hello,world!

sandwich.textContent='Hello,world!';//也可以添加//Hello,world!Andhi,Universe!

sandwich.innerText+='Andhi,Universe!';区别似乎是做同样的事情,那么它们之间有什么区别呢?Node.textContent属性获取整个文本内容,包括那些不在元素内部呈现给页面的内容。Element.innerText只是返回呈现的文本,类似于可以用光标和键盘选择的文本部分。举个例子就清楚了。p{color:rebeccapurple;}这不是渲染的。

Helloworld!

letgreeting=document.querySelector('.greeting');/*returnp{color:rebeccapurple;}Thisisnotrendered.Helloworld!*/lettext1=greeting.textContent;//return"Helloworld!"lettext2=greeting.innerText;终于知道有区别了!躺着又学到了一个知识点~本文转载自微信公众号「1024翻译站」,可以通过以下二维码关注。转载请联系1024翻译站公众号。