issues inserting a div from Javascript - 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/

Related

Issue with getElementById and similar calls on dynamically created elements

Uncaught TypeError: Cannot read property 'style' of null
No matter what I've tried I cannot get any of the javascript methods to identify each individual div created with unique IDs. Does anyone see where I'm messing up the call to find the div with specified ID and update it's css styling?
I also cannot seem to dynamically create an object with an onclick event to toggle what details are shown. I've tried to create individual buttons with an on-click event for the above event but can't get it to stick unless I hard code a button in rather than dynamically creating it.
without the last function included everything runs as expected and each div has a unique id but with the last function the program breaks before any of the elements can be created.
Javascript
function createTable() {
var list = document.querySelector('#table')
var toAdd = document.createDocumentFragment();
var id = '0';
for(var i = 0; i < 7; i++) {
var identifier = document.createElement('div');
identifier.id = id;
identifier.className = 'item';
identifier.innerHTML = standards[i].identifier;
toAdd.appendChild(identifier);
id++;
var description = document.createElement('div');
description.id = id;
description.className = 'description';
description.innerHTML = standards[i].statement;
var extended = document.createElement('div');
extended.id = 'r' + i;
extended.className = 'standard extra';
extended.innerHTML = standards[i].description;
description.appendChild(extended);
toAdd.appendChild(description);
id++;
var subconcept = document.createElement('div');
subconcept.id = id;
subconcept.className = 'subitem';
subconcept.innerHTML = standards[i].subconcept;
toAdd.appendChild(subconcept);
id++
var practices = document.createElement('div');
practices.id = id;
practices.className = 'subitem';
practices.innerHTML = standards[i].practices;
toAdd.appendChild(practices);
id++;
var link = document.createElement('p');
link.className = 'link';
link.innerHTML = "more...";
link.onclick = displaySubinfo(id);
toAdd.appendChild(link);
}
list.appendChild(toAdd);
}
function displaySubinfo(id) {
var elem = document.getElementById(id);
elem.style.display = "inline";
elem = document.getElementById(id - 1);
elem.style.display = "inline";
}
HTML
<!DOCTYPE html>
<html>
<head>
<link href="site.css" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title class="page-title">Computer Science Standards</title>
</head>
<body>
<script src="standards.js"></script>
<script src="site.js"></script>
<div id="table">
<div class="column-name">
Identifier
</div>
<div class="column-name">
Standard
</div>
<div class="column-name">
Subconcept
</div>
<div class="column-name">
Practices
</div>
<script>createTable()</script>
</div>
<script>
</script>
</body>
</html>
This part won't work:
link.onclick = displaySubinfo(id);
what that does is call the displaySubinfo function right away, and assign the return value (undefined) to the onclick event.
It seems that you wouldn't need any of the IDs if the displaySubInfo function was able to work without parameters, so:
function displaySubinfo(e) {
// get the element that was clicked
var elem = e.target;
elem.style.display = "inline";
// also change the previous element
var prev = elem.previousElementSibling;
prev.style.display = "inline";
}
What the heck's e? Event object containing useful stuff like the element that was clicked. We get that for free if we wire up your function like this:
var link = document.createElement('p');
link.className = 'link';
link.innerHTML = "more...";
link.addEventListener("click", displaySubinfo);

Creating div on button click with Javascript not working?

I have a button in a webpage that is linked to a Javascript function, which creates a div as follows:
function creatediv(){
var div = document.createElement('div');
div.innerHTML = document.getElementById('innerhtmlbox').value;
document.body.appendChild(div);
}
However, it is not working. Can anyone give me any advice?
Try this:
function createDiv() {
let div = document.createElement('div');
div.innerText = document.getElementById('getText').innerText;
document.body.appendChild(div);
}
<button onClick="createDiv()">Click me!</button>
<div id="getText" style="display: none;">
INNER TEXT
</div>
You need to use innerText
function creatediv() {
var div = document.createElement('div');
div.innerHTML = document.getElementById('innerhtml').textContent;
document.body.appendChild(div);
}
creatediv();
http://jsfiddle.net/e8jn9pj5/3/
Or if you are populating it from button's value you may use .value as suggested by adeneo http://jsfiddle.net/t4c5yq24/

Dynamically created nested Div's not rendering JavaScript

I have a piece of JavaScript which is meant to be dynamically creating a nested set of Div's in my application. The parent Div is being created just fine, however the inner Div is not rendering at all.
Any help would be great!
JavaScript:
function createWindow()
{
var note_window = document.createElement("div");
note_window.setAttribute("id", "note_window");
note_window.setAttribute("class", "notification-window");
note_window.style.visibility = 'visible';
var title = document.createElement("div");
title.setAttribute("id", "title");
title.setAttribute("class", "col-md-12");
title.innerHTML = "Notifications";
note_window.appendChild(title);
var navbar = document.getElementById("navbar");
navbar.appendChild(note_window);
}
Rendered HTML:
<div id="note_window" class="notification-window" style="visibility: visible;">
Text
</div>
Desired HTML:
<div id="note_window" class="notification-window" style="visibility: visible;">
Text
<div id="title" class="col-md-12">
More Text
</div>
</div>
EDIT:
Thanks for your help guys, I have partly answered my own question...
Further down in my code there is another function which edits the contents of note_window.
if (document.getElementById("note_window") == null)
{
createWindow();
if (getNotifications() == null) {
note_window.innerHTML = "Text"
}
}
When I comment out the code for setting the innerHTML, both Div's render correctly... Now the question is... Why!?
Are you looking for this?
var note_window;
var title;
function createWindow()
{
note_window = document.createElement("div");
note_window.setAttribute("id", "note_window");
note_window.setAttribute("class", "notification-window");
note_window.style.visibility = 'visible';
//note_window.innerHTML = "Text";
title = document.createElement("div");
title.setAttribute("id", "title");
title.setAttribute("class", "col-md-12");
title.innerHTML = "Notifications";
note_window.appendChild(title);
var navbar = document.getElementById("navbar");
navbar.appendChild(note_window);
}
function getNotifications() {
return null;
}
if (document.getElementById("note_window") == null)
{
createWindow();
if (getNotifications() == null) {
var text = document.createTextNode('Text');
title.parentNode.insertBefore(text, title);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="navbar">some content</div>
Or this (in case everything needs to be created dynamically via JavaScript):
http://plnkr.co/edit/3pNmY3UnqbgZWpSFVH66?p=preview
function createWindow()
{
var note_window = document.createElement("div");
var title = document.createElement("div");
var navbar = document.createElement("div");
note_window.setAttribute("id", "note_window");
note_window.setAttribute("class", "notification-window");
note_window.style.visibility = 'visible';
title.setAttribute("id", "title");
title.setAttribute("class", "col-md-12");
title.innerHTML = "Notifications";
navbar.setAttribute("id", "navbar");
note_window.appendChild(title);
navbar.appendChild(note_window);
document.getElementsByTagName('body')[0].appendChild(note_window);
}
And the HTML markup
<body onload="createWindow()"></body>
Your code seems to be working for me, I've just modified the text to match to your example. I have a jsfiddle https://jsfiddle.net/yye4dsqm/3/
function createWindow() {
var note_window = document.createElement("div");
note_window.setAttribute("id", "note_window");
note_window.setAttribute("class", "notification-window");
note_window.style.visibility = 'visible';
note_window.innerHTML = 'Text';
var title = document.createElement("div");
title.setAttribute("id", "title");
title.setAttribute("class", "col-md-12");
title.innerHTML = "More Text";
note_window.appendChild(title);
var navbar = document.getElementById("navbar");
navbar.appendChild(note_window);
}
createWindow();
Seems so simple now...
In my edit I mention that I am setting the innerHTML of the parent DIV, this is then overriding the entire child DIV with text. Setting a break point after the initial creation shows the elements rendered correctly.
I wasn't seeing it before as I was only looking at the elements after the call had been made to set the innerHTML.
Thanks guys!
Outside perspective always helps! :)

div - createElement is not working?

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>

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?

Categories