[英]Manipulating DOM with JavaScript
下面的代碼應該在我的文檔中添加p
元素,在此元素中添加文本,並將該元素的字體顏色更改為red
。
這是一堂課。 我已經為此工作了兩個小時,但是很困惑。
<!DOCTYPE html>
<html>
<body>
<h1 id='demo'>
THE TITLE OF YOUR WEBPAGE
</h1>
<div id="container">
<div class="content">
This is the glorious text-content!
</div>
</div>
</body>
<script>
const p = document.createElement('p');
p.textContent = 'Hey, I'm red.';
p.style.color = 'red';
div.content.appendChild('p');
</script>
</html>
該代碼無法產生預期的結果。 你們中的任何一個都可以幫助我了解我所缺少的嗎?
您的代碼中有幾個問題:
您正在使用的textContent無效( 'Hey, I'm red.'
)。
您可以使用雙引號將整個字符串括起來,以便可以在字符串內部使用單引號,例如"Hey, I'm red."
。
或者:您可以使用反斜杠( \\
)來對內引號進行轉義,例如'Hey, I\\'m red.'
或者:您可以使用模板文字將帶有反斜線的字符串包裝起來,例如:
`Hey, I'm red.`
您必須使用document.getElementById()
來定位元素。
appendChild('p')
變量p周圍的引號,否則,引號會將其視為字符串而不是變量 : const p = document.createElement('p'); p.textContent = "Hey, I'm red."; p.style.color = 'red'; document.getElementById('container').appendChild(p);
<h1 id='demo'> THE TITLE OF YOUR WEBPAGE </h1> <div id="container"> <div class="content"> This is the glorious text-content! </div> </div>
這里'Hey, I'm red.';
,您需要使用反斜杠對'm
之前的引號進行轉義,否則您可以在雙引號內添加雙引號。
在div.content.appendChild('p');
旁邊div.content.appendChild('p');
在這里div需要成為一個目標,您可以使用document.getElementById
&在appendChild
內獲取總線,您需要將p
作為變量傳遞
const p = document.createElement('p'); p.textContent = 'Hey, I\\'m red.'; p.style.color = 'red'; document.getElementById('container').appendChild(p);
<h1 id='demo'> THE TITLE OF YOUR WEBPAGE </h1> <div id="container"> <div class="content"> This is the glorious text-content! </div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.