I'm trying to learn how to program in JavaScript, coming from a pretty solid knowledge of Java, HTML, and CSS. I've styled a website using bootstrap to play around with but I'm already stuck. My goal is the change the background color of the navbar elements using plain JavaScript
I can do this using jQuery, but I need to know how to program in JavaScript as its helpful to have as a skill. After researching this, The implementations I can see are the mouseover attribute of HTML elements and getElementsByClassName/getElementsById.
When I implement them myself I can't seem the have any luck at all. I'd like to keep my JavaScript inside an external file which is another difficulty. I can't seem to select all the elements at once, let alone style them.
Here's my html (using Bootstrap 4 and some custom stylings):
<!DOCTYPE = html>
<html lang = "en">
<head>
<title>Testing Styles</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap-grid.css">
<link rel="stylesheet" type="text/css" href="css/styles.css">
<link href="https://fonts.googleapis.com/css?family=Julius+Sans+One|Quicksand|Rubik" rel="stylesheet">
</head>
<body>
<heading>
<div class = "Jumbotron">
<h1 class = "display-2">The Header</h1>
<p class = "lead subtext"> And Subtext about the header</p>
</div>
</heading>
<nav class = "mx-auto bg-dark">
<div class = "container-fluid">
<ul class = "nav justify-content-center">
<li class = "nav-item active" id = "temp">
<a class = "nav-link text-light" href="#">Homepage</a>
</li>
<li class = "nav-item active" id = "temp">
<a class = "nav-link text-light" href="#">Posts</a>
</li>
<li class = "nav-item active" id = "temp">
<a class = "nav-link text-light" href="#">Report A Problem</a>
</li>
</ul>
</div>
</nav>
<script src= "JS/scripts.js"></script>
</body>
</html>
JavaScript:
document.getElementsByClassName("nav-link").style.color = "blue";
Setting the color to blue is only testing if the selection worked, not my final goal. When I refresh the page nothing happens. I've confirmed I linked my JS file correctly as alert() works.
getElementsByClassNamereturns a list, not a single element. You need to iterate the elements and add amouseoverevent listener.Element.getElementsByClassName()gives you an Array Like Object. It would be likedocument.getElementsByClassName('nav-link')[0].style.color = 'blue';for the first Array Like Object Element.