gpt4 book ai didi

javascript - Vanilla Javascript/DOM 练习帮助(添加红色页脚段落)

转载 作者:行者123 更新时间:2023-11-28 07:01:54 26 4
gpt4 key购买 nike

我的 HTML 代码:

 <html>
<head>
<link rel="stylesheet" href="styles.css" media="screen" title="no title" charset="utf-8">
<title>Vanilla</title>
</head>

<body>
<section id="header">
<h1 id="page-title">Vanilla DOM</h1>
<div id="image-container">
<img height="100px" src="http://upload.wikimedia.org/wikipedia/commons/c/c0/Vanilla_Ice.jpg" alt="Vanilla Ice" />
</div>
<p id="description">
Vanilla JavaScript can be awesome. Here's why.
</p>
<ul id="awesome-list">
<li class="awesome-list-item">It is built into JavaScript.</li>
<li class="awesome-list-item">Everybody loves vanilla.</li>
<li class="awesome-list-item">Everybody loves Vanilla.</li>
</ul>
</section>

<script type="text/javascript" src="scripts.js"></script>
</body>
</html>

我想做的是在页面中添加一个红色的页脚段落,id 为“page-footer”。因为它是一个页脚段落,所以我假设它必须放在结束部分标记之后。这是我尝试但不起作用的方法:

 var redFooter = document.createElement("id");
redFooter.setAttribute("id", "page-footer");
redFooter.setAttribute("style", "color: red;");
var section = document.getElementById("header");
section.appendChild(redFooter);
var redFooter = document.getElementByClass("page-footer");
var newParagraph = "This is a new red paragraph";
redFooter.innerHTML = newParagraph;

我想知道我做错了什么。有人可以指出这个问题吗?谢谢。

最佳答案

简单问题:当您应该使用 getElementById 时,您却使用了 getElementByClass:

这是一个有效的修复程序(点击“运行代码段”以查看其运行情况):

var redFooter = document.createElement("div");
redFooter.setAttribute("id", "page-footer");
redFooter.setAttribute("style", "color: red;");
document.getElementById("header").appendChild(redFooter);
var redFooter = document.getElementById("page-footer");
var newParagraph = "This is a new red paragraph";
redFooter.innerHTML = newParagraph;
<body>
<section id="header">
<h1 id="page-title">Vanilla DOM</h1>
<div id="image-container">
<img height="100px" src="http://upload.wikimedia.org/wikipedia/commons/c/c0/Vanilla_Ice.jpg" alt="Vanilla Ice" />
</div>
<p id="description">Vanilla JavaScript can be awesome. Here's why.</p>
<ul id="awesome-list">
<li class="awesome-list-item">It is built into JavaScript.</li>
<li class="awesome-list-item">Everybody loves vanilla.</li>
<li class="awesome-list-item">Everybody loves Vanilla.</li>
</ul>
</section>
</body>

关于javascript - Vanilla Javascript/DOM 练习帮助(添加红色页脚段落),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33182373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com