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);
Related
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>
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>");
}
I want to make it so i append a link at the end of each row, but it says "Click Here", and then it openes a link? Ill show you my code below but i dont know really how to work this out, iv been thinking for 2 hours now and came up with nothing...
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
var row = tblUsers.insertRow(rowIndex);
var cellId = row.insertCell(0);
var cellMovieName = row.insertCell(1);
var cellPrice = row.insertCell(2);
var cellLink = row.insertCell(3);
cellId.appendChild(document.createTextNode(childKey));
cellMovieName.appendChild(document.createTextNode(childData.Title));
cellPrice.appendChild(document.createTextNode(childData.Price));
cellLink.appendChild(document.createTextNode("CLICK ME" with the href attribute of childData.Title));
rowIndex = rowIndex + 1;
I think you need to do like this
You can't append child like that you need to do like
var list = document.getElementById("idhere");
var button = document.createElement('button');
button.value = "Click Me";
list.appendChild(button);
Now you can add attributes
var attribute = document.createAttribute("id"); // Can be class data-id whaterver you want onclick, anything you want
attribute.value = "time"; // can be anything
button.setAttributeNode(attribute);
// Some Examples
var span2 = document.createElement('span');
span2.innerText = snapshot.val().message;
var span_2_ID = document.createAttribute("id");
span_2_ID.value = "post";
// Time
var span3 = document.createElement('span');
span3.innerText = snapshot.val().time;
var span_3_ID = document.createAttribute("id");
span_3_ID.value = "time";
span1.setAttributeNode(span_1_ID);
span2.setAttributeNode(span_2_ID);
span3.setAttributeNode(span_3_ID);
var break1 = document.createElement('br');
var break2 = document.createElement('br');
I hope this helps you
Ok I figured it out... with a little bit of both of your guys's knowlage you have provided, i made a solution to this check below:
var text = document.createTextNode("This is link");
var link = document.createElement('a');
link.setAttribute('href', "https://google.com");
link.setAttribute('html', "test");
link.setAttribute('target', "_blank");
link.appendChild(text);
cellLink.appendChild(link);
rowIndex = rowIndex + 1;
So I Made The Text, Added It To The Column And Then Added The Attributes I Appreciate Everyone Helping Me!
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.
I am unable to find any solution of adding DOM elements with text nodes and adding number index in the nodes only using javascript.
I've tried using if..else and for loop but none of them work.
function addElement() {
var para = document.createElement("p");
var add = document.createTextNode("This is newly added. ");
para.appendChild(add);
var element = document.getElementById("div1");
element.appendChild(para);
}
You can append one label element inside the p element with the current length of p as the text of the label:
function addElement() {
var length = document.querySelectorAll('p').length;
var para = document.createElement("p");
var add = document.createTextNode("This is newly added. ");
var label = document.createElement("label");
label.textContent = length + ' ';
para.appendChild(label);
para.appendChild(add);
var element = document.getElementById("div1");
element.appendChild(para);
}
document.getElementById('createElement').addEventListener('click',addElement);
<button type="button" id="createElement">Create Element</button>
<div id="div1"></div>