Javascript appendChild not working for li element - javascript

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.

Related

How to create multiple paragraphs with Javascript with shorter code?

I want to create multiple paragraphs with each two inputfield with Javascript.
I wanted to know, if there is a way to have a shorter code but the same result?
It should have the same result like this but with a shorter code:
var para1 = document.createElement("p");
var i1 = document.createElement("input");
var i2 = document.createElement("input");
para1.appendChild(i1);
para1.appendChild(i2);
var element = document.getElementById("div1");
element.appendChild(para1);
var para2 = document.createElement("p");
var i3 = document.createElement("input");
var i4 = document.createElement("input");
para2.appendChild(i3);
para2.appendChild(i4);
var element = document.getElementById("div1");
element.appendChild(para2);
var para3 = document.createElement("p");
//etc.
<div id="div1"></div>
I could not think of any other solution than using a for loop 😁
This definitely reduces the code by half length though.
numberOfParagraphs = 3
for(let i = 0; i< numberOfParagraphs;i++){
var para= document.createElement("p");
var i1 = document.createElement("input");
var i2 = document.createElement("input");
para.appendChild(i1);
para.appendChild(i2);
document.getElementById("div1").appendChild(para);
}
<div id="div1"></div>
Wrap your code into a function
function createPara() {
var para1 = document.createElement("p");
var i1 = document.createElement("input");
var i2 = document.createElement("input");
para1.appendChild(i1);
para1.appendChild(i2);
var element = document.getElementById("div1");
element.appendChild(para1);
}
Call the function n times
createPara()
createPara()
Additionally you can pass params such as class, id etc.
well the way you have it written, you are executing the exact same code multiple times. why not put it in a function?
createPara();
createPara();
createPara();
//etc.
function createPara() {
var para2 = document.createElement("p");
var i3 = document.createElement("input");
var i4 = document.createElement("input");
para2.appendChild(i3);
para2.appendChild(i4);
var element = document.getElementById("div1");
element.appendChild(para2);
}
Create a document fragment and append it to DIV instead of creating individual elements.
In the current setup, HTML elements will reflow each time you append any element.
With DocumentFragment you can save multiple reflows as it reflows only once when attached.
Please refer https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment for information.
wrap your code into a function and give it number of para :
function createPara(n) {
let parentDiv = document.getElementById("div1")
for(let i =0; i<n; i++){
let para = document.createElement("p");
let i1 = document.createElement("input");
let i2 = document.createElement("input");
para1.appendChild(i1);
para1.appendChild(i2);
parentDiv.appendChild(para);
}
}
}
Call the function and give it the number u want to repeat for exemple 5 time :
createPara(5)
you can also give it the number of inputs
I thought I would do something for a more general case, but might have gotten a bit carried away; anyway:
const new_children = [
{ tag: 'p', children: [
{ tag: 'input' },
{ tag: 'input' },
] },
];
const element_for_def = (def) => {
const element = document.createElement(def.tag);
if(def.children && def.children.length > 0)
append_children_to_ele(element, def.children);
return element;
};
const append_to_element = (parent) => (child) => parent.appendChild(child);
const append_children_to_ele = (parent, children) =>
children
.map(element_for_def)
.forEach(append_to_element(parent));
const three_new_children = [1,2,3].reduce(acc => acc.concat(new_children), []);
append_children_to_ele(document.getElementById("div1"), three_new_children);
<div id="div1"></div>
ma is a reference to an element object which you want to create multiple paragraphs.
I use 10 for multiple paragraphs line. You can use your required number.
let ma = document.getElementById("multiple-para").innerHTML;
for(var i =0; i<10; i++){
document.write(ma + "<br>");
}

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.

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

Using onclick in javascript to create a new div inside a div created using onclick itself?

I created a div consisting of radio button inputs using onclick from a radio button input inside a form in php and then i again attempted to create another div using onclick from inside this created div but only the outer div is being created. Would like to know where i am wrong..
<input id="sub" type="radio" name="opt1" value="2" onclick="createDiv4()"> Academic User<br/>
function createDiv4() {
if(document.getElementById("acad_")==null)
{
var divi = document.createElement("div");
divi.id="acad_";
divi.style.height="100px";
//divi.style.marginTop="200px";
var cont = document.getElementById('contain');
cont.appendChild(divi);
var p = document.createElement("label");
var disp = document.createTextNode("Please select the type of User :");
p.appendChild(disp);
p.style.textSize="16px";
p.style.textAlign="left";
divi.appendChild(p);
var b1 = document.createElement("BR");
divi.appendChild(b1);
var ip = document.createElement("input");
ip.name="wo";
ip.value="1";
ip.type="radio";
ip.onclick="createDiv4_1()";
ip.style.marginRight="4px";
divi.appendChild(ip);
var labe = document.createElement("label");
var labe_val = document.createTextNode("Technical Institute");
labe.appendChild(labe_val);
divi.appendChild(labe);
var b = document.createElement("BR");
divi.appendChild(b);
var ip2 = document.createElement("input");
ip2.name="wo";
ip2.value="2";
ip2.type="radio";
ip2.style.marginRight="4px";
ip2.onclick="createDiv4_1()";
divi.appendChild(ip2);
var labe2 = document.createElement("label");
var labe_val2 = document.createTextNode("School");
labe2.appendChild(labe_val2);
divi.appendChild(labe2);
if(document.getElementById("govt")!=null)
{
var de = document.getElementById("govt");
de.parentNode.removeChild(de);
}
}
else
{
var divi1 = document.getElementById("acad_");
divi1.parentNode.removeChild(divi1);
}
}
</script>
<script>
function createDiv4_1() {
if(document.getElementById("school")==null)
{
var divi = document.createElement("div");
divi.id="school";
//divi.style.marginTop="200px";
var cont = document.getElementById('contain');
cont.appendChild(divi);
var p = document.createElement("label");
var disp = document.createTextNode("Please select the type of User for Workshop :");
p.appendChild(disp);
p.style.textSize="16px";
p.style.textAlign="left";
divi.appendChild(p);
var b1 = document.createElement("BR");
divi.appendChild(b1);
var ip = document.createElement("input");
ip.name="wo";
ip.value="1";
ip.type="radio";
ip.style.marginRight="4px";
divi.appendChild(ip);
var labe = document.createElement("label");
var labe_val = document.createTextNode("School Student");
labe.appendChild(labe_val);
divi.appendChild(labe);
var b = document.createElement("BR");
divi.appendChild(b);
var ip2 = document.createElement("input");
ip2.name="wo";
ip2.value="2";
ip2.type="radio";
ip2.style.marginRight="4px";
divi.appendChild(ip2);
var labe2 = document.createElement("label");
var labe_val2 = document.createTextNode("Teacher");
labe2.appendChild(labe_val2);
divi.appendChild(labe2);
var b2 = document.createElement("BR");
divi.appendChild(b2);
var ip2 = document.createElement("input");
ip2.name="wo";
ip2.value="2";
ip2.type="radio";
ip2.style.marginRight="4px";
divi.appendChild(ip2);
var labe3 = document.createElement("label");
var labe_val3 = document.createTextNode("Parent");
labe3.appendChild(labe_val3);
divi.appendChild(labe3);
if(document.getElementById("govt")!=null)
{
var de = document.getElementById("govt");
de.parentNode.removeChild(de);
}
}
else
{
var divi1 = document.getElementById("school");
divi1.parentNode.removeChild(divi1);
}
}
</script>
You arent calling the functions properly. Instead of :
ip.onclick= "createDiv4_1()";
This is only a string, it won't call it. You put it in quotes in the HTML but in JavaScript you don't need to. Also get rid of the parenthesis in JS. So use this :
ip.onclick= createDiv4_1;
Working fiddle : https://jsfiddle.net/thatOneGuy/xgvqwcq4/2/
I added a div with ID contain for this to work too.
according to your question title you have two option.
forget about onclikc inside the html and use normal js
document.getElementById("secondDiv").addEventListener("click", function () {
newFunctionI();
})
/*JQ version*/
$("#secondDiv").on("click", function () {
newFunctionI();
})
second way is: use jquery append() or html();
function yourFunctionI() {
$("#ID").append("<div id='secondDiv' onclick='newFunction()'> new </div>")
}

HTML DOM - element.appendChild() doesn't behave as I expect it to

link to code (js and css can be found through the page source): https://dl.dropboxusercontent.com/u/16952797/webdev/uppg1/kontakt.html
alt link: http://jsfiddle.net/DdQhk/ (although jsfiddle does not render the page properly)
relevant lines of code (function createFormBug() - line 31 to 66 in kontakt.js)
code:
function createFormBug() {
var form = document.createElement("form");
var fieldset = document.createElement("fieldset");
var legend = document.createElement("legend");
var labelFunction = document.createElement("label");
var labelInterface = document.createElement("label");
var labelComment = document.createElement("label");
var radioFunction = document.createElement("input");
radioFunction.type = "radio";
var radioInterface = document.createElement("input");
radioInterface.type = "radio";
var textarea = document.createElement("textarea");
var buttonSubmit = document.createElement("input");
radioInterface.type = "submit";
form.id = "formBug";
legend.textContent = "Bugg";
document.getElementById("divForm").appendChild(form);
form.appendChild(fieldset);
fieldset.appendChild(legend);
fieldset.appendChild(labelFunction);
fieldset.appendChild(radioFunction);
fieldset.appendChild(labelInterface);
fieldset.appendChild(radioInterface);
fieldset.appendChild(labelComment);
fieldset.appendChild(textarea);
fieldset.appendChild(buttonSubmit);
}
context: I'm trying to create a form dynamically by using js, unfortunately some elements aren't being appended for some reason.
partial output of generated html when run on Chrome (relevant section):
<div id="divForm">
<form id="formBug">
<fieldset>
<legend>Bugg</legend>
<label></label>
<input type="radio">
<label></label>
<input type="submit">
<label></label>
<textarea></textarea>
<input>
</fieldset>
</form>
</div>
I think your code is working pretty much as you might expect it to. The only obvious mistake is that you are setting radioInterface.type = "submit"; where you presumably mean buttonSubmit.type = "submit";.
It should be apparent that this works fine if you actually put some content in to make elements like label actually visible...
Something like this, perhaps?
var form = document.createElement("form");
var fieldset = document.createElement("fieldset");
var legend = document.createElement("legend");
var labelFunction = document.createElement("label");
labelFunction.textContent = 'Function'; // <-- added
var labelInterface = document.createElement("label");
labelInterface.textContent = 'Interface'; // <-- added
var labelComment = document.createElement("label");
labelComment.textContent = 'Comment'; // <-- added
var radioFunction = document.createElement("input");
radioFunction.type = "radio";
var radioInterface = document.createElement("input");
radioInterface.type = "radio";
var textarea = document.createElement("textarea");
var buttonSubmit = document.createElement("input");
buttonSubmit.type = "submit"; // <-- corrected
I believe your code to actually add them to the document should be working fine.

Categories