Jump to content

The appendChild not working!


koorosh13hm

Recommended Posts

Hi everyone,

I have been trying to fix this issue by visiting the forums here and there

and also tried to do exactly what I learned from them yet, I am unable

to add a div to another one. The error message in the console is :

 

Uncaught TypeError: Cannot read property 'appendChild' of undefined

 

And the code that I have been using is as follows. Could you please help me with this issue?

 

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>1js</title>
<style type="text/css">
div.box {
background-color: hsl(0, 0%, 0%);
margin-left: 15px;
width: 20px;
height: 20px;
}
div.wrapper {
width: 400px;
height: 200px;
background-color: green;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper"> </div>
<script type="text/javascript">
var wrappers = document.getElementsByClassName("wrapper");
var newDiv = document.createElement("div.box");
document.wrappers.appendChild(newDiv);
}
</script>
</body>
</html>
Link to comment
Share on other sites

getElementsByClassName() returns a node list, not an HTML element. A node list is like an array. Use square brackets to access an element in the node list.

 

You wouldn't use document.wrappers to access the wrappers variable, just use wrappers on its own since it's a variable referencing the node list.

Link to comment
Share on other sites

Actually I have tried this line of command too:

 

var wrappers = document.getElementsByClassName("wrapper")[0];

 

and have removed document as told, But there is no trace of any new div shown!!!!!

Edited by koorosh13hm
Link to comment
Share on other sites

Actually I have tried this line of command too:

 

var wrappers = document.getElementsByClassName("wrapper")[0];

 

and have removed document as told, But there is no trace of any new div shown!!!!!

In the chrome Inspect Element section yhe width and height of the div.box is shown as 0.

Link to comment
Share on other sites

You're not creating an element <div> with classname "box", what you're doing is creating an element <div.box>.

 

If you want to add a class name to an element, change its className property:

var newDiv = document.createElement("div");newDiv.className = "box";
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...