Reputation:
I can't understand why I am getting this error:
Uncaught TypeError: Cannot read property 'appendChild' of undefined
Here is my code:
//create new div element, append it to the body, give it an ID and a Class.
const container_clause_1 = document.createElement("div");
document.body.appendChild(container_clause_1);
container_clause_1.setAttribute("id", "container_clause_1");
container_clause_1.classList.add("cc1");
console.log(container_clause_1);
//returns <div id="container_clause_1" class="cc1></div>"
const cClause1 = document.getElementById("container_clause_1");
console.log(cClause1);
//returns <div id="container_clause_1" class="cc1></div>"
const right_clause_1 = document.createElement("div");
console.log(right_clause_1); //returns <div></div>
document.cClause1.appendChild(right_clause_1); //Error occurs here!
I don't understand what is undefined in this situation. cClause1
is define. right_clause_1
is also defined. Granted, it's an empty div at this point, but that is what I am trying to do - add the div and then I can add the class and id, etc.
Also, I don't see any typos.
Also, if I replace document.cClause1.appendChild(right_clause_1);
with document.body.appendChild(right_clause_1);
it works fine. Except that I don't want it inside the body, but rather, inside the container_clause_1 div.
I can't use JQuery for this. "Why not" is not really germane to the question. I have my reasons. Just understand that I can't use JQuery.
Well that was so obvious - after everyone started pointing out what I did wrong! Thanks for the answers!
Just another thing that this pointed out to me:
I can eliminate the variable cClause
and just use container_clause_1
so my code is shorter!
const container_clause_1 = document.createElement("div");
document.body.appendChild(container_clause_1);
container_clause_1.setAttribute("id", "container_clause_1");
container_clause_1.classList.add("cc1");
const right_clause_1 = document.createElement("div");
container_clause_1.appendChild(right_clause_1);
right_clause_1.setAttribute("id", "right_clause_1");
right_clause_1.classList.add("r1");
Upvotes: 1
Views: 58
Reputation: 2875
Why have "document." in this line?
document.cClause1.appendChild(right_clause_1);
Surely you only need:
cClause1.appendChild(right_clause_1);
Upvotes: 1