[Edit: Thanks to Ganesh's answer, it led me on the right track to what the actual problem was. So thanks for that. The problem was in my for
loop I have let i = 0, str = ""
, which meant I was creating a new str
for the loop, which was different than the str
outside the loop. This meant when I set el.innerHTML = str
outside the loop, it was not the str
that had been created in the loop.]
I am creating a w3.css
dropdown with canvases and labels in it. I am basing it on the example with the title 'Clickable Dropdowns' on the webpage W3.CSS Dropdowns.
<div class="w3-dropdown-click">
<button onclick="OnClickDoStuff()" class="w3-button w3-black">
<canvas id="imageMain"></canvas>
<label id="labelMain">Name</label>
</button>
<div id="divInnards" class="w3-dropdown-content w3-bar-block w3-border">
<!-- Stuff inserted with javascript -->
</div>
</div>
I am adding the elements of divInnards
in javascript.
let el = document.getElementById("divInnards");
let str, iStr;
for(let i=0, str = "";i < 24; i++){
iStr = i.toString();
str += "<a href=\"#\" class=\"w3-bar-item w3-button\""
+ " id=\"divLink" + iStr + "\""
+ " onclick=\"OnClickLink(" + iStr + ")\""
+ ">"
+ "<canvas id=\"divCanvas" + iStr + "\" ></canvas>"
+ " "
+ "<label id=\"divLabel" + iStr + "\">Name</label>"
+ "</a>";
}
el.innerHTML = str;
However, then when I try and get divCanvas0
later on, I get null.
let cnv = document.getElementById("divCanvas0"); // cnv === null :(
What am I doing wrong?