![1617782992913330.jpg 如何在JS中改變DOM元素的文字內容](https://img.php.cn/upload/image/440/919/297/1617782992913330.jpg)
在JavaScript
中取得元素只是第一步,如何對元素的屬性進行變更才是接下裡的重要步驟,本文主要講述如何在JS
中更改DOM
元素的內容。
HTML表單內容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!DOCTYPE html>
<html lang= "en" >
<head>
<meta charset= "UTF-8" >
<meta http-equiv= "X-UA-Compatible" content= "IE=edge" >
<meta name= "viewport" content= "width=device-width, initial-scale=1.0" >
<title>Document</title>
</head>
<body>
<div class = "box" >
<p></p>
</div>
</body>
</html>
|
登入後複製
1.textContent:
1 2 3 4 5 6 7 8 9 | <script>
const box=document.querySelector( ".box" );
console.log(box);
const p=document.querySelector('p');
console.log(p);
p.textContent = "hello world" ;
</script>
|
登入後複製
2.innerText:
1 2 3 4 5 6 7 8 | <script>
const box=document.querySelector( ".box" );
console.log(box);
const p=document.querySelector('p');
console.log(p);
p.innerText = "php.cn" ;
</script>
|
登入後複製
3.innerHTML:##
1 2 3 4 5 6 7 8 | <script>
const box=document.querySelector( ".box" );
console.log(box);
const p=document.querySelector('p');
console.log(p);
p.innerHTML='<em style= "color:red" >php.cn</em>';
</script>
|
登入後複製
推薦:《
2021年js面試題目及答案(大總結)》
以上是如何在JS中改變DOM元素的文字內容的詳細內容。更多資訊請關注PHP中文網其他相關文章!