Selecting with meteor

#1

Hello everyone,

I’m totally new in meteor.
I made this tutorial : http://meteortips.com, it was great.
However, I’m struggling at the start of my first project for a very simple thing and I don’t see answer on the web about that.

Here is my HTML :

<head>
    <title>Stormchess</title>
</head>
<body>
    <h1> Chessboard </h1>
    {{> chessboard}}
</body>

<template name="chessboard">
    <div id="chessboard">
    <!-- … -->
    <img class="square" src="images/blacksquare.png" alt="Black Square" />
    <!-- … -->
    </div>
</template>

The thing is, I want to put attribute draggable to false to all my img tags ; so, I start like I’d do without meteor.
Here is my client main.js :

import { Template } from 'meteor/templating';
import './main.html';
var squares = document.querySelectorAll(".square");
for(var i=0; i<squares.length; i++){
    squares[i].draggable = "false";
}

And this simple thing doesn’t work. So i try to troubleshoot ==>;

var squares = document.querySelectorAll(".square");
console.log(squares);

In console, i’ve a null, which is my problem but i don’t understand why.

Even stranger : if i do :

var squares = document.querySelectorAll("body");
console.log(squares);

In this case, the console display me the body and all that’s within, my img tags included !!!
But if i try querySelector(".square"), or querySelector(“img”), or even querySelector(“h1”), the console display null. -_-’’’

I guess (and hope) the answer is simple but I can’t figure out my mistake and I’m blocked since hours on this … so I post here.

#2

Hehe, yes, your browser is messing with you a bit here I think.

When your code runs, the only thing that exists in the browser is the body. When you print the body element in the console, you get a reference to that node that you can open up, which chrome updates as your app starts rendering the other elements. So by the time you open it up, all the stuff is in there, even if it wasn’t there when you initially printed the thing.
This is the reason the other elements won’t work, as initially they don’t exist, so you don’t get that auto-updating reference in the console.

Your code doesn’t work because it runs before the template has rendered (blaze templates are created by javascript after all). So what you need to do is to run your code inside an onRendered function.

#3

Thank you jorgeer !!

I tried within the onCreated function but with your explanation, i understand why it didn’t worked. Now it works ! Here is the code for anyone who would have similar issue :

import { Template } from 'meteor/templating';
import './main.html';
Template.chessboard.onRendered(function(){
	var squares = document.querySelectorAll(".square");
	for(var i=0; i<squares.length; i++){
		squares[i].draggable = false;
	}
});

Have a good day !