Reputation: 11
the script only works if it's within the "hamburger" div, and I have no clue why? Why doesn't it work if I have it in the body or in the head? Also, I can't for the life of my have it worke if I export it to a .js file and src it into the HTML. HELP PLEASE? This is my first site and I'm already completely floored by such a simple problem....
<!DOCTYPE html>
<html lang="it" dir="ltr">
<head>
<meta charset="utf-8">
<link href="styles.css" rel="stylesheet"/>
<title>My Azienda Agricola</title>
</head>
<body>
<header>
<nav>
<div class="hamburger">
<script>
let test=document.getElementsByClassName("hamburger");
test[0].style.backgroundColor="blue";
</script>
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
</nav>
</header>
</body>
</html>
Upvotes: 0
Views: 103
Reputation: 1503
Use document.querySelector()
instead of document.getElementsByClassName()
It's a more state of the art way to do selectors, see here.
apart from this, your .hamburger
has no width or height and cant be displayed blue if its 0px.
As you can see i added a width and height of 50px and the blue square is appearing. i didn't had your stylesheet.
this is a working example of what u try to do:
<!DOCTYPE html>
<html lang="it" dir="ltr">
<head>
<meta charset="utf-8" />
<title>My Azienda Agricola</title>
<style>
.hamburger {
width: 50px;
height: 50px;
}
</style>
</head>
<body>
<header>
<nav>
<div class="hamburger">
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
</nav>
</header>
<script>
let test = document.querySelector(".hamburger");
test.style.backgroundColor = "blue";
</script>
</body>
</html>
You can also with this example here: https://codesandbox.io/s/vigilant-resonance-yxpp9?file=/index.html
Upvotes: 1
Reputation: 3
What I would do this this:
<!DOCTYPE html>
<html lang="it" dir="ltr">
<head>
<meta charset="utf-8">
<link href="styles.css" rel="stylesheet"/>
<title>My Azienda Agricola</title>
</head>
<body>
<header>
<nav>
<div class="hamburger">
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
</nav>
</header>
<script src="javascript.js"></script>
</body>
</html>
Then create your javascript.js file and add your script in there. Make sure it's in the same root folder as your .html file. If you put it in a folder, make sure you adjust the src according (e.g. js/javascript.js).
Upvotes: 0
Reputation: 11
Try to put the script tag before the end of the body tag, since it won't validate outside the body or head tags. See here for more information.
Upvotes: 0