我试图将 className 设置给我的导航元素,但结果与预期不符。当我手动将类添加到 HTML 时,它会在无序列表项和按钮周围加上边框。然而,当我使用 js 添加时,检查器显示导航标签具有该属性,但实际上并没有添加边框,因此我认为它没有生效。我做错了什么?我在文件中链接了 bootstrap cdn 和 jquery cdn。
HTML
<!doctype html>
<html lang="en-us">
<head>
<title>Exercise 5.9</title>
<meta charset="UTF-8">
<meta equiv="X-UA-Compatible" content="IE=Edge">
</head>
<body id="content">
<!-- Latest compiled and minified CSS -->
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<nav>
<div>
<ul>
<li>Home</li>
<li>Our Policies</li>
<li>How you can help</li>
<li>What we have accomplished</li>
<button type="button">Donate $10.00</button>
<button type="button">Donate $50.00</button>
<button type="button">Donate $100.00</button>
</ul>
</div>
</nav>
<p>If you would to offer financial support, please choose the buttons above</p>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="exercise-5.9.js"></script>
</body>
</html>
JS
var nav = document.getElementsByTagName("nav");
nav.className = "navbar navbar-default";
console.log(nav);
var nav = document.getElementsByTagName("nav")[0];
,因为你想获取第一个 nav 元素。 - NewToJSgetElementsByTagName
返回一组节点数组。 - Andyconsole.log(nav);
,那为什么没有注意它的类型呢? - Joaquín O