HTML tag to javascript createElement - javascript

I'm having a lot of problems trying to write an HTML code in Javascript DOM. This website is my last hope.
I want to convert this HTML tag:
<div class="received_msg">
<div class="received_withd_msg">
<p>
<b>Username: </b> Hello everyone!
</p>
</div>
</div>
This is what I have written so far:
var div2 = document.createElement('div');
div2.className = 'received_msg';
var div3 = document.createElement('div');
div3.className = 'received_withd_msg';
var par = document.createElement('p');
var bold = document.createElement('b')
div2.innerHTML += div3.outerHTML;
par.innerHTML += bold.innerHTML + data.username + ' : ' + data.msg;
document.querySelector('#message').append(div2);
document.querySelector('#message').append(par);
The above javascript code doesn't print out the HTML code that I want. What's the proper way to do it?
Note that data.username and data.msg are variables referenced in the full code.

You should be appending the elements you create to their parent elements
var div2 = document.createElement('div');
div2.className = 'received_msg';
var div3 = document.createElement('div');
div3.className = 'received_withd_msg';
var par = document.createElement('p');
var bold = document.createElement('b');
bold.textContent = "hello";
// var boldTxt = document.createTextNode("Hello");
// bold.appendChild(boldTxt);
var txt = document.createTextNode(" World");
div2.appendChild(div3);
div3.appendChild(par);
par.appendChild(bold);
par.appendChild(txt);
document.body.append(div2);

Writing HTML using vanilla JS might be truly confusing :) As written above, appending children to parent elements would be easier and better in many ways. Just to complete the whole idea with your case and all the variables:
var data = {username: 'John Doe', msg: 'Hello World!'};
var root = document.querySelector('#root');
var div2 = document.createElement('div');
div2.className = 'received_msg';
var div3 = document.createElement('div');
div3.className = 'received_withd_msg';
var par = document.createElement('p');
var bold = document.createElement('b');
bold.textContent = `${data.username}: `;
par.appendChild(bold);
var text = document.createTextNode(data.msg);
par.appendChild(text);
div3.appendChild(par);
div2.appendChild(div3);
root.appendChild(div2);
<div id="root"></div>

Related

How to append two block elements in to a div?

Not sure what I am doing wrong. I know <p> and <h1> are block elements but even with display: inline-block; nothing happens. H1 still overrides the P tag. What am I doing wrong? I've tried multiple methods, I'm sure it's really simple.
The code is below.
let newContent = document.createElement('div');
newContent.classList.add('new');
let mewOne = document.createElement('h1');
newContent.style.cssText = 'border-color: black; background-color:pink;';
mewOne.textContent ="hey, i'm in a div";
let mewTwo = document.createElement('p');
mewTwo.textContent ="me too";
container.appendChild(mewOne, mewTwo);
full code ------
Html
JS
const container = document.querySelector('#container');
const content = document.createElement('div');
content.classList.add('content');
content.textContent = 'My first dom manipulation!';
container.appendChild(content);
//first//
let newContent = document.createElement('div');
newContent.classList.add('new');
let mewOne = document.createElement('h1');
newContent.style.cssText = 'border-color: black; background-color:pink;';
mewOne.textContent ="hey, i'm in a div";
let mewTwo = document.createElement('p');
mewTwo.textContent ="me too";
container.appendChild(mewOne, mewTwo);
//second//
const contentHeading = document.createElement('h3');
contentHeading.classList.add('new');
contentHeading.textContent = "i'm blue h3!";
contentHeading.style.color = 'blue';
container.appendChild(contentHeading);
//third///
const contentParagraph = document.createElement('p');
contentParagraph.classList.add('new');
contentParagraph.textContent ="Hey i'm red";
contentParagraph.style.color = 'red';
container.appendChild(contentParagraph);
//fourth//

Appending created elements to different divs in Javascript

I have the following code:
JS :
i.addEventListener("click", function () {
var br1 = document.createElement("br");
var div1 = document.createElement("div");
div1.className = "input-group";
var ipt1 = document.createElement("input");
ipt1.type = "text";
ipt1.className = "form-control";
var span = document.createElement("span");
span.className = "input-group-addon";
var ipt2 = document.createElement("input");
ipt2.type = "text";
ipt2.className = "form-control";
div1.appendChild(ipt1);
div1.appendChild(span);
div1.appendChild(ipt2);
divdiv.appendChild(div1);
divdiv.appendChild(br1);
});
document.getElementById('modal2body').appendChild(divdiv);
However, when there are multiple <i>s, the divdiv is appended to the last one.
This is all in a for loop, which adds an <i> for each element in a list.
The list might look like ['customers','employees','managers','night-shifts']
There needs to be an option to add the input-group to each one of these. (the i is a FontAwesome 'plus' icon).
The problem I have, is that clicking any of the icons, it will add the input-group to the night-shift list.
I thought I might need to use dynamic variables to fix this.
If it happens that this is the most effective solution, how can I achieve this?
Or is there a better way to do this ?
Screenshot :
In this screenshot, I clicked the + to the right of Customers
This code creates the original 4 input-groups (1 for each section) :
var divdiv = document.createElement('div');
divdiv.id = 'd' + d;
var div1 = document.createElement('div')
div1.className = 'input-group';
var ipt1 = document.createElement('input');
ipt1.type = 'text';
ipt1.className = 'form-control'
var span = document.createElement('span');
span.className = 'input-group-addon';
var ipt2 = document.createElement('input');
ipt2.type = 'text';
ipt2.className = 'form-control'
var div2 = document.createElement('div');
var t = document.createElement('t');
t.className = 'helv-b grey'
t.style.fontSize = '15px';
t.textContent = inputstext[d];
div2.appendChild(t);
var i = document.createElement('i');
i.className = 'fa fa-plus';
i.style.float = 'right'
i.style.fontSize = '20px';
i.style.marginTop= '5px'
i.onmouseenter = i.style.opacity = "60%";
i.onmouseleave = i.style.opacity = "100%";
div2.appendChild(i);
var br1 = document.createElement('br');
var br2 = document.createElement('br');
divdiv.appendChild(div2);
divdiv.appendChild(br1);
div1.appendChild(ipt1);
div1.appendChild(span);
div1.appendChild(ipt2);
divdiv.appendChild(div1);
divdiv.appendChild(br2);
divdiv.id = 'f' + d;
(inputstext = ['Customers','Employees','Managers','Night-Shifts'])
HTML :
<div class="modal-body" id="modal2body">
</div>
###Update
Screenshots :
I can't figure out how to fix these alignment issues and make them look like my original screenshot.
Also, how do I have 1 input-group already displayed for each section ?
The problem is that the code which adds is event-driven, which means that it will run when the user clicks the add icon. So when the add icon is click the value of divdiv will be the last element of array "Night-Shifts".
Here is a way of doing it using arrays.
var inputstext = ['customers', 'employees', 'managers', 'night-shifts']
var divdivArray = [];
var mainDiv = document.getElementById("modal2body");
for (var d = 0; d < inputstext.length; d++) {
var divdiv = document.createElement('div');
divdiv.id = 'd' + d;
var div1 = document.createElement('div')
div1.className = 'input-group';
var ipt1 = document.createElement('input');
ipt1.type = 'text';
ipt1.className = 'form-control'
var span = document.createElement('span');
span.className = 'input-group-addon';
var ipt2 = document.createElement('input');
ipt2.type = 'text';
ipt2.className = 'form-control'
var div2 = document.createElement('div');
var t = document.createElement('t');
t.className = 'helv-b grey'
t.style.fontSize = '15px';
t.textContent = inputstext[d];
div2.appendChild(t);
var i = document.createElement('i');
i.className = 'fa fa-plus';
i.style.float = 'right'
i.style.fontSize = '20px';
i.style.marginTop = '5px'
i.onmouseenter = i.style.opacity = "60%";
i.onmouseleave = i.style.opacity = "100%";
i.setAttribute("index", d)
div2.appendChild(i);
var br1 = document.createElement('br');
var br2 = document.createElement('br');
divdiv.appendChild(div2);
divdiv.appendChild(br1);
div1.appendChild(ipt1);
div1.appendChild(span);
div1.appendChild(ipt2);
divdiv.appendChild(div1);
divdiv.appendChild(br2);
divdiv.id = 'f' + d;
mainDiv.appendChild(divdiv)
divdivArray.push(divdiv);
i.addEventListener("click", function() {
var br1 = document.createElement("br");
var div1 = document.createElement("div");
div1.className = "input-group";
var ipt1 = document.createElement("input");
ipt1.type = "text";
ipt1.className = "form-control";
var span = document.createElement("span");
span.className = "input-group-addon";
var ipt2 = document.createElement("input");
ipt2.type = "text";
ipt2.className = "form-control";
div1.appendChild(ipt1);
div1.appendChild(span);
div1.appendChild(ipt2);
var index = this.getAttribute("index");
divdivArray[index].appendChild(div1);
divdivArray[index].appendChild(br1);
});
}
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<div class="modal-body" id="modal2body" style="display: inline-block;">
</div>
<html>
Here I save every divdiv inside the array. And also add an index attribute to the <i> element so when it is clicked you can know which divdiv you want to edit.

Javascript appendChild not working for li element

My JavaScript code works up to the last append. This I checked with alert messages. All the alerts except for the last one get displayed. So I assume the problem is with the last append. Can someone please help?
var node = document.createElement("li");
var d0 = document.createElement("div");
var d1 = document.createElement("div");
var L1 = document.createElement("label");
d1.append(L1);
L1.innerHTML = "datah[key]";
var d2 = document.createElement("div");
var L2 = document.createElement("label");
d2.append(L2);
L2.innerHTML = "datah1[key]";
console.log("test1");
d0.append(d1);
d0.append(d2);
node.append(d0);
console.log("test2");
document.getElementById("speclist").appendChild(node);
// The following alert doesn't get printed
console.log("test3");
<div>
<ul id="speclist">
</ul>
</div>
There is no problem with last append problem is that you are not wrapping "test3" in any html.you want to show test3 then you have to wrap it with node(li).
var node = document.createElement("li");
var d0 = document.createElement("div");
var d1 = document.createElement("div");
var L1 = document.createElement("label");
d1.append(L1);
L1.innerHTML = "datah[key]";
var d2 = document.createElement("div");
var L2 = document.createElement("label");
d2.append(L2);
L2.innerHTML = "datah1[key]";
alert("test1");
d0.append(d1);
d0.append(d2);
node.append(d0);
alert("test2");
//document.getElementById("speclist").appendChild(node);
// The following alert doesn't get printed
alert("test3");
node.appendChild(document.createTextNode("test3"));
document.getElementById("speclist").appendChild(node);
<div>
<ul id="speclist">
</ul>
</div>
and one more thing when i am running your code it is showing me 3 alerts test1,test2 and test3.

Document.createElement("br") not working with multiple calls to appendChild

HTML
var x = document.createElement("p");
var br1 = document.createElement('br');
var br2 = document.createElement('br');
var t5 = document.createTextNode("CSE");
var t6 = document.createTextNode("EEE");
x.appendChild(t5);
x.appendChild(br1);
x.appendChild(t6);
x.appendChild(br2);
document.getElementById("new").appendChild(x);
The output should look like
CSE
EEE
but now the output is CSEEEE
The issue here is with the br element you created. It is unique. So at first when you append it to its place in the DOM, it sits in between the t5 and t6 element. However, when you append the br element a second time, it places it in a different location in the DOM and that is why you see the result of CSEEEE followed by only 1 br element.
You should either omit the last one, or clone the br element.
var x = document.createElement("p");
var br = document.createElement('br');
var t5=document.createTextNode("CSE");
var t6=document.createTextNode("EEE");
x.appendChild(t5);
x.appendChild(br);
x.appendChild(t6);
x.appendChild(br.cloneNode());
document.getElementById("new").appendChild(x);
<div id="new">
you can't reuse the same elemnt
var x = document.createElement("p");
var t5=document.createTextNode("CSE");
var t6=document.createTextNode("EEE");
x.appendChild(t5);
x.appendChild(document.createElement('br'));
x.appendChild(t6);
x.appendChild(document.createElement('br'));
document.getElementById("new").appendChild(x);
You have to create two <br>
var x = document.createElement("p");
var br1 = document.createElement('br');
var br2 = document.createElement('br');
var t5 = document.createTextNode("CSE");
var t6 = document.createTextNode("EEE");
x.appendChild(t5);
x.appendChild(br1);
x.appendChild(t6);
x.appendChild(br2);
document.getElementById("new").appendChild(x);

Javascript erasing old elements using html

I have sliders which gives user chance to choose time range . Based on this time range some messages printed in the screen with some style. I am kinda generating style for those messages between following tags.
<section> .... </section>
When I change my slider values which determines the range of the new messages, the new ones come behind old messages. I just want the all messages from the new range not old one .
You can see jsFiddle of my code also here
$(function() {
$( "#slider-5" ).slider({
range:true,
min: parseInt(ctime[0]),
max: parseInt(ctime[ctime.length-1]),
values: [ parseInt(ctime[4]),parseInt(ctime[len])],
change: function( event, ui ) {
$( "#slidevalue" )
.val( formatDateTime(ui.values[ 0 ]) + " - " + formatDateTime(ui.values[ 1 ]) );
new_var=ui.values[0];
var body = document.getElementsByTagName('body')[0];
var section = document.createElement('section');
section.id = 'cd-timeline';
section.className = 'cd-container';
body.appendChild(section);
for (var x=0;parseInt(ctime[x])<ui.values[0];x++);
for (var x = 0;parseInt(ctime[x])<=ui.values[1]; x++) {
var datum = new Date(parseInt(ctime[x]));
var outerDiv = document.createElement('div');
outerDiv.className = 'cd-timeline-block';
section.appendChild(outerDiv);
var div = document.createElement('div');
div.className = 'cd-timeline-img cd-location';
outerDiv.appendChild(div);
var img = document.createElement('img');
img.src = 'img/cd-icon-location.svg';
img.setAttribute('alt', 'Location');
div.appendChild(img);
var div = document.createElement('div');
div.className = 'cd-timeline-content';
outerDiv.appendChild(div);
var h2 = document.createElement('h2');
div.appendChild(h2);
h2_text = document.createTextNode('foo');
h2.appendChild(h2_text);
var p = document.createElement('p');
div.appendChild(p);
p_text = document.createTextNode(<?php echo json_encode($content); ?>[x]);
p.appendChild(p_text);
var span = document.createElement('span');
span.className = 'cd-date';
div.appendChild(span);
span_text = document.createTextNode(formatDateTime(datum));
span.appendChild(span_text);
}
}
});
});
If i understood correctly, (it appears to be correct from comments) You don't need to append new <section> every time the slider is changed (If you're doing this note that you can't use the same id for multiple elements).
Have the <section> in HTML, like
<section id="cd-timeline" class="cd-container"></section>
then you can replace it's content using $('#cd-timeline').html(); as follows:
$(function() {
$( "#slider-5" ).slider({
range:true,
min: parseInt(ctime[0]),
max: parseInt(ctime[ctime.length-1]),
values: [ parseInt(ctime[4]),parseInt(ctime[len])],
change: function( event, ui ) {
$( "#slidevalue" )
.val( formatDateTime(ui.values[ 0 ]) + " - " + formatDateTime(ui.values[ 1 ]) );
new_var=ui.values[0];
for (var x=0;parseInt(ctime[x])<ui.values[0];x++);
for (var x = 0;parseInt(ctime[x])<=ui.values[1]; x++) {
var datum = new Date(parseInt(ctime[x]));
var outerDiv = document.createElement('div');
outerDiv.className = 'cd-timeline-block';
$('#cd-timeline').html(outerDiv); // replace the content of existing section
var div = document.createElement('div');
div.className = 'cd-timeline-img cd-location';
outerDiv.appendChild(div);
var img = document.createElement('img');
img.src = 'img/cd-icon-location.svg';
img.setAttribute('alt', 'Location');
div.appendChild(img);
var div = document.createElement('div');
div.className = 'cd-timeline-content';
outerDiv.appendChild(div);
var h2 = document.createElement('h2');
div.appendChild(h2);
h2_text = document.createTextNode('foo');
h2.appendChild(h2_text);
var p = document.createElement('p');
div.appendChild(p);
p_text = document.createTextNode(<?php echo json_encode($content); ?>[x]);
p.appendChild(p_text);
var span = document.createElement('span');
span.className = 'cd-date';
div.appendChild(span);
span_text = document.createTextNode(formatDateTime(datum));
span.appendChild(span_text);
}
}
});
});
How to remove the section: $("section").remove();
How to remove its children: $("section").children().remove();
Before appending child elements to the 'section' you can say
$('section').children().remove();
to get rid of everything within the 'section'
This will take everything inside of your section and remove it. Be careful though. If you have other elements within your section already, those will be removed too. If you want to avoid that. Put your content that will be added and the stuff to be removed inside of an element that is seperate from the other content.
Like this
<section>
<div>
//all your other content
</div>
<div id='sliderContent'>
//all your slider content
</div>
</section>
Then in your jquery use instead
$('section #sliderContent').children().remove();
This will make it so you do not have to append a section to the dom anymore

Categories