Reputation: 169
I want to do a changing to certain span
elements based in their id
.
So i give each one of div
and span
an id
, and then i try to .style.color
each of the span
.
but an error is to be seen : Cannot read property 'style' of null"
I don't know what i am doing wrong.
Here is a simple reproductible model of my program
for (y = 0; y < 7; y++) {
let colonne = document.createElement("div");
colonne.className = "horaire_one";
colonne.id = ("col" + y);
for (x = 0; x < 26; x++) {
let span = document.createElement("span");
span.className = "pasdispo_one_rpv";
span.id = (colonne.id + x);
document.getElementById(span).style.color = "green";
}
}
Upvotes: 1
Views: 55
Reputation: 8584
You're not passing an id to document.getElementById, you're passing an element. Besides, it wouldn't work anyway, as you never added the element to the document. Fortunately, since you already have the element, you don't need to use document.getElementById. Simply do:
span.style.color = "green";
If you wanted to change colonne
instead, simply replace span
with colonne
.
Upvotes: 1
Reputation: 207511
You are trying to reference an element from the DOM before you add it to the DOM. You are not going to find it. You already have a reference to the span when you created it.
for (let y = 0; y < 7; y++) {
let colonne = document.createElement("div");
colonne.className = "horaire_one";
colonne.id = "col" + y;
for (let x = 0; x < 26; x++) {
let span = document.createElement("span");
span.className = "pasdispo_one_rpv";
span.id = colonne.id + (x + y * 26);
span.style.color = "green";
span.textContent = x + y * 26;
colonne.appendChild(span);
}
document.body.append(colonne);
}
.pasdispo_one_rpv {
border: 1px solid black;
width: 1.4em;
display: inline-block;
}
Upvotes: 2
Reputation: 2703
Two problems here:
creating element is not enough. You need to add it to the DOM somehow. Google for 'appendChild'
document.getElementById(span).style.color = "green";
it should have span.id in the brackets
And just a note:
document.getElementById(span).style.color = "green";
in your code, because span
is already in a loop. You can change to span.style.color = 'green';
Upvotes: 0