Reputation:
I'm trying to create the div
tag using javascript.? But why it is not working?
I have seen the document.createElement not working
Javascript createElement() not working in Chrome But these answers are not suited for my script.
<html>
<head>
<script>
var div = '<div id = con style="width:auto; height:200px; Background:#2a2a2a">';
var x = document.createElement(div);
var y = document.getElementById('con');
y.innerHTML = "hello world";
document.body.appendChild(x);
</script>
</head>
<body>
</body>
</html>
How can I do it?
Upvotes: 2
Views: 3269
Reputation: 236162
It doesn't work like so. .createElement()
only excepts the type of element you want to create, no predefined HTML snippet. So you have to create a Div Element using document.createElement('div');
and work on that element afterwards. Like
For Instance
var div = document.createElement('div');
div.id = 'con';
div.style.cssText = "width:auto; height:200px; Background:#2a2a2a";
document.body.appendChild( div );
If you don't need a reference to an Element and you only want to insert new HTML code, you can also use Element.prototype.insertAdjacentHTML()
like so
document.body.insertAdjacentHTML( 'beforeend', '<div id="con" style="width:auto; height:200px; Background:#2a2a2a">');
A further problem of your code here is that you try to access the DOM too early. Even if the code would work in its current form, you cannot access document.body
in your <head>
section because it wasn't fully initialized at that point. Either move the entire <script>
source into the <body>
section or attach a listener to DOMContentLoaded
Event.
Upvotes: 5
Reputation: 193301
If you want to insert entire HTML structure all at once, you can use very useful, cross-browser and unfairly little known insertAdjacentHTML
method:
var div = '<div id="con" style="width:auto; height:200px; Background:#2a2a2a"></div>';
document.body.insertAdjacentHTML('beforeend', div);
var y = document.getElementById('con');
y.innerHTML = "hello world";
Upvotes: 3
Reputation: 388436
You cannot create a predefined html like that, also since you are appending to body, the script should be inside the body element not in head
<html>
<head>
</head>
<body>
<script>
var x = document.createElement('div');
x.id = 'con';
x.style.width = 'auto';
x.style.height = '200px';
x.style.background = '#2a2a2a';
x.innerHTML = "hello world";
document.body.appendChild(x);
//no need to access `y` by id, use the reference returned by createElement to set the content
//var y = document.getElementById('con');
//y.innerHTML = "hello world";
</script>
</body>
</html>
Upvotes: 1