Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Jeremy Diallo
3,846 PointsquerySelectorAll returning an empty node list
Hi, I'm trying to animate a webpage for the first time by using a code I found in the Eloquent JavaScript book. Unfortunately, it's not working.
Here's my HTML :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Environment</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src="script.js"></script>
<p style="text-align: center; margin-top: 100px">
<img src="thumbnail.png" alt="wordpress-logo" style="position: relative">
</p>
</body>
</html>
And here's my JavaScript :
var image = document.querySelectorAll("img");
var angle = 0, lastTime = null;
function animate(time) {
if (lastTime != null)
angle += (time - lastTime) * 0.001;
lastTime = time;
image.style.top = (Math.sin(angle) * 20) + "px";
image.style.left = (Math.cos(angle) * 200) + "px";
requestAnimationFrame(animate);
}
When I call the image object with my browser's console, it returns an empty NodeList while there is obviously an img element on the HTML document. When I call image.style in the console, it says that image.style is undefined while my image definitely has a style attribute.
Am I missing something in my program ?
1 Answer
Gunhoo Yoon
5,027 PointsThat probably has to do with 'when' your script is running. In a nutshell, your script runs before it sees img tag hence doesn't find any img tag. If you are not using JQuery and trying to interact with DOM you should put your script tag as far as possible otherwise your script only knows about half finished document. Try putting script tag at the end of body. If it doesn't work let me know.