div - createElement is not working? - javascript

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?

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.

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";

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>

Related

how to show html when using appendChild

I'm creating some elements through this code in JavaScript:
var tdiv = document.createElement("div");
tdiv.setAttribute('id', 'titlediv');
var ddiv = document.createElement("div");
ddiv.setAttribute('id', 'datediv');
var cdiv = document.createElement("div");
cdiv.setAttribute('id', 'contentdiv');
Now I have to append some html text to cdiv. I tried to do cdiv.appendChild() but it displays an error since it is not a node. Tried doing var newsupdate_ = document.createTextNode(global[j].content) then appending it but it looks like this:
Can I do setAttribute to place the content inside the desired div?
appendChild() would not work in cdiv because there is no such method present in the element created by createElement().
createTextNode() creates a new Text node. It will not evaluate any HTML present in the parameter string.
Try innerHTML like the following way:
var cdiv = document.createElement("div");
cdiv.setAttribute('id', 'contentdiv');
cdiv.innerHTML = '<h1>Header 1</h1>';
document.getElementById('container').append(cdiv);
<div id="container"></div>
use innerHTML, example
document.getElementById("demo").innerHTML = "Paragraph changed!";

How to dynamically change a background image of a div using pure javascript

What will be the syntax to change the background-image of body using javascript
How to fix the error in line y.style.background = '' + "url(1.jpg) no-repeat" + '';
Markup :
<!DOCTYPE html>
<html>
<head>
<style>
body {
//this is the style for body tag
background: url("heart.png") no-repeat;
color: red;
}
</style>
</head>
<body>
<h3><p id="hello">This Is Heart.</p>
</h3>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.getElementById("hello"); //this is id of paragraph
var y = document.getElementsByTagName("body"); //id of background element
var z = document.getElementById('myImg');
y.style.background = '' + "url(1.jpg) no-repeat" + ''; //y error what will be the code to replace background-image of div
</script>
</body>
</html>
If you want to change the backgorund image of your body, you can do this
document.body.style.backgroundImage = "url(1.jpg)";
document.body.style.backgroundRepeat = "no-repeat";
//OR
document.body.style.background = "url(1.jpg) no-repeat";
Update:
document.getElementsByTagName("body") returns a collection(like an array) of elements with tag body. Since we have only one body we will use document.getElementsByTagName("body")[0].
See the docs.
Your main problem is probably (though you might want to add the actual error message to your question) that getElementsByTagName() returns an array of DOM elements and not a single one. So if you change to
var y = document.getElementsByTagName("body")[0]; //array will contain a single element
y.style.background = 'url(1.jpg) no-repeat'; //No need for your funky empty string concatenation
I think you should be good.

Dynamic div containing selected text inside another div

I have a div element. I will copy-paste some text in this div. Then, upon clicking a create button, another div will be created inside the div with the selected text inside it. The new div will have a different background-color, different fonts, and other style properties. But my code isn't working. Please help me to figure out the mistakes. Thanks!!
<html>
<head>
<title>select</title>
<style>
</style>
</head>
<body>
<script>
function changeit(){
var slctn = document.getSelection();
var strings = slctn.toString();
alert(strings);
var get_id = document.getElementById("myspace");
var elem = document.createChild("div");
var design = document.createAttribute("style");
design.value = "background-color:white;color:red;font-weight:bold;font-style:italic;font-family:CURSIVE;";
elem.setAttributeNode(design);
elem.createTextNode(now);
get_id.appendChild(elem);
alert("it is done");
}
</script>
<div contenteditable="true" width="400px" height="500px" style="background-color:pink;display:block;" id="myspace">ddd</div>
<input type="button" value="select" onClick="changeit();">
</body>
</html>
For create div element you should use
var elem = document.createElement("div");
instead of
var elem = document.createChild("div");
And createTextNode is performed over document something like
document.createTextNode('now');
Working DEMO
<script>
function changeit(){
var slctn=document.getSelection();
var strings=slctn.toString();
alert(strings);
document.getElementById("myspace").appendChild('<div style="background-color:white;color:red;font-weight:bold;font-style:italic;font-family:CURSIVE;">'+document.getElementById("myspace").innerHTML+'</div>');
}
</script>
Works?

issues inserting a div from Javascript

I'm trying to add a div with some text before another div in the document.
Here's my script in a nutshell, assume init() gets called when onload page:
<head>
<script type="text/javascript">
function init () {
var div = document.createElement('div').className = 'title';
div.innerHTML = 'Hello';
var reference = document.getElementById('content');
document.body.insertBefore(div, reference );
}
</script>
</head>
<body>
<div id="content">blah blah</div>
<br /><br />
</body>
I get a type mismatch error on document.body.insertBefore(div, reference), Can someone please let me know what i'm doing wrong?
Try
function init () {
var div = document.createElement('div');
div.className = 'title';
div.innerHTML = 'Hello';
var reference = document.getElementById('content');
document.body.insertBefore(div, reference );
}
You were setting the div to the string title I think (never checked)
Yep here you go
http://jsfiddle.net/FxFzc/

documentFragement

please take a look at the following code.
var oFra = document.createDocumentFragment();
var myDiv = document.createElement("div");
myDiv.id="myId";
oFra.appendChild(myDiv);
oFra.getElementById("myId");
In this case do i have ref to the div i just inserted inside documentFragement using the variable myDiv?
Lets say i move ahead and add this documentFragement to the actual DOM. Will I still be able to access the div with id="myId" using this "myDiv" variable???
If you try this, it works:
http://www.jsfiddle.net/dactivo/4BSaF/
The problem is that you cannot use "oFra" + getElementById directly, once you append the fragment, you can access the div "myId" in the DOM.
<div id="test"></div>
<script type="text/javascript">
var oFra = document.createDocumentFragment();
var myDiv = document.createElement("div");
myDiv.id="myId";
myDiv.innerHTML="hola";
oFra.appendChild(myDiv);
// oFra.getElementById("myId");
document.getElementById("test").appendChild(oFra);
alert(document.getElementById("myId").innerHTML);
</script>

Categories