Jump to content
koorosh13hm

The appendChild not working!

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>

Share this post


Link to post
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.

Share this post


Link to post
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

Share this post


Link to post
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.

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...