Dynamically created nested Div's not rendering JavaScript - 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! :)

Related

Creating a div by pressing a button [duplicate]

This question already has answers here:
Click through div to underlying elements
(17 answers)
Closed 2 years ago.
I was trying to create Divs by clicking a button but it just fill the button range with red.
<div class="app">
<button onclick="createDiv()">Make a cube</button>
</div>
<script>
function createDiv ()
{
var boxEle = document.querySelector('.app');
boxEle.style.width = 100;
boxEle.style.height = 100;
boxEle.style.backgroundColor = '#f00';
}
</script>
Your not off by much. You were selecting the div you already created in the html, and some of your js syntax is off.
Try this jsFiddle
function createDiv ()
{
var boxEle = document.createElement('div');
var container = document.querySelector('.app');
boxEle.style.width = '100px';
boxEle.style.height = '100px';
boxEle.style.backgroundColor = '#f00';
container.appendChild(boxEle);
}
Firstly , in your function you are selecting an already created div in your html, so you are not creating a div. If you want to create a div using javascript you can do it like this.
function createDiv() {
let box = document.createElement('div'); // creates div
box.classlist.add('box-styling') // you can add a class and style it using that instead
let container = document.querySelector('.container') // div has to be placed somewhere in html, so create a container and select it.
container.appendChild(box) // then append to container
}
This should do it:
<div class="app">
<button onclick="createDiv()">Make a cube</button>
</div>
<script>
function createDiv () {
var boxEle = document.querySelector('.app');
var newDiv = document.createElement('div');
newDiv.style.width = 100;
newDiv.style.height = 100;
newDiv.style.margin = 5;
newDiv.style.backgroundColor = '#f00';
boxEle.appendChild(newDiv);
}
</script>

Shortest way to create a DIV

What would be the shortest way to do the following :
var div = document.createElement('div');
div.className = 'divClass';
div.innerHTML = 'Div Content';
... without any external libraries
class Div {
constructor(className, innerHTML) {
let div = document.createElement("div");
div.className = className;
div.innerHTML = innerHTML;
return div;
}
}
let innerHTML = "LOL"
new Div(divClass, innerHTML);
This would be the shortest way to doing it again and again while still having some order inside your code, IMO.
Write a function to do it in one line:
function tag(tagNameAndClass, innerHTML) {
var parts = (tagNameAndClass || 'div').split(/\./g);
var elem = document.createElement(parts.shift());
elem.className = parts.join(' ');
if (innerHTML) elem.innerHTML = innerHTML;
return elem;
}
Examples of uses:
tag('div.divClass', 'Div Content') // <div class="divClass">Div Content</div>
tag('.class-one.class-two', 'Content') // <div class="class-one class-two">Content</div>
tag('h1.super', 'My Super Heading') // <h1 class="super">My Super Heading</h1>
What would be the shortest way to do the following [...]
We can imagine a situation in which the div already exists in the DOM while the CSS style rule display:none ensures it remains absent from the visible document flow.
The following single line in javascript will make the element reappear into the visible document flow:
document.getElementsByClassName('divClass')[0].style.display = 'block';
Probably the best solution I have came up with so far :
var el = function(type,props,appends){
var el = document.createElement(type);
if(props) for(var x in props) el[x] = props[x];
if(appends) for(var x in appends) el.appendChild(appends[x]);
return el;
}
and then when using it (creating a popup with header and body example) :
$title = el('div',{className:'title',innerHTML:'Item Title'});
$remove = el('div',{className:'remove',innerHTML:'X'});
$header = el('div',{className:'header'},[$title,$remove,el('div',{className:'clear'})]);
$body = el('div',{className:'body',innerHTML:'body'});
$el = el('div',{className:'item'},[$header,$body]);

Javascript appendChild if div not exists

i've working in a big project, and that i want is
if div 1 not contain div 2 child{
div1.appendChild(div2)
}
But, i'm getting problem to solve this
My code
<script>
dc = document.createElement("div");
dc.className = "doctor_card doctor-"+o+" hidden";
dcc.appendChild(dc);
</script>
Thanks for advice :)
Try this:
<script>
var className = "doctor_card doctor-"+o+" hidden";
if (dcc.getElementsByClassName(className).length == 0) {
dc = document.createElement("div");
dc.className = className;
dcc.appendChild(dc);
}
</script>
var dcc = document.getElementsByClassName('parentclass')[0];
if (!dcc.contains(dc)) {
dcc.appendChild(dc);
}
You can use above code if u really want to use pure javascript.

Why isn't my appendChild working with createDocumentFragment?

I am trying to append newly created elements to a div, then append the div to a document fragment, but it isn't working as expected. Please help me identify what I am missing.
//array of values to look up
let channels = ["channel1", "channel2", "channel3","channel4","channel5","channel6","channel7","channel8","channel9","channel10","channel11","channel12","channel13","channel14","channel15","channel16"];
//jsonp request function defined
function streamRequest () {
//identify DOM elements for final appendChild
let docFrag = document.createDocumentFragment();
let container = document.getElementById("main-container");
//create container and elements for the acquired information
let div = document.createElement("div");
let image = document.createElement("img");
let p = document.createElement("p");
let p1 = document.createElement("p");
let p2 = document.createElement("p");
//variables for request responses
let logo;
let name;
let status;
let game;
channels.forEach(function channelsRequest(channel){
$.getJSON("https://api.twitch.tv/kraken/streams/" + channel + "?callback=?", function callback(data) {
if(data.stream === null){
status = "Offline"
game = "Offline"
} else if (data.stream != null) {
status = "Online"
game = data.stream.game
}
console.log(channel, status, game);
$.getJSON("https://api.twitch.tv/kraken/channels/" + channel + "?callback=?",function logoRequest(data) {
name = data.display_name;
if(data.logo === null) {
logo = "http://www.logowik.com/uploads/images/379_twitch.jpg"
} else if (data.logo != null) {
logo = data.logo
}
//set attributes and inner HTML for new elements
image.setAttribute("src",logo);
image.setAttribute("alt","photo of channel's image");
image.className = "image";
p.innerHTML = name;
p.className = "name";
p1.innerHTML = status;
p1.className = "status";
p2.innerHTML = game;
p2.className = "game";
//append elements to the div
div.appendChild(image)
div.appendChild(p)
div.appendChild(p1)
if(status === "Online"){
div.appendChild(p2)
}
div.className = "tv-block";
docFrag.appendChild(div);
console.log(data, name, logo, docFrag);
});
});
});
//append final document fragment to the DOM
container.appendChild(docFrag);
};
`
From what I understand, you should be able to append everything to the a div, then append the div to the fragment. When I run the code, nothing is amended to the DOM. I think it may be because of scoping, or the second json request isn't set up properly
I know this answer comes a year later but as I've just completed the same challenge I thought it might make sense to share my solution as I also had the same problem. It looks like creating a new DOM element and appending all generated divs to it and then appending this element to an existing DOM element is faster than using document fragment. So my structure looks like this:
<body>
<main>
<header>
</header>
</main>
<footer>
</footer>
</body>
And then I append to the main a div#container created in js and containing all generated divs.
Here is a link to the completed project.

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/

Categories