I am creating a dynamic form with many different divs inside. Each div has its own unique input combination. I have read that appendChild is faster than changing the innerHTML so my solution is to build number of arrays. Each array is a div in the form and in each array there are several objects defined. Each object is an input.
eg:
var div = [
label = {
tag: "label",
text: "Enter password",
for: "pass"
},
input = {
tag: "input",
type: "password",
name: "pass"
}
];
At first, I used a foreach statement to attach the object's property onto a new element using setAttribute like so: (while using a 'tag' property as the html tag and than deleting it so it will not appear as an attribute).
for(var elem in div) {
var temp = document.createElement(div[elem].tag);
delete div[elem].tag;
for(var prop in div[elem]) {
temp.setAttribute(prop,input[prop]);
}
parentDiv.appendChild(temp);
}
The problem is I have more things I would like to add to the element that cannot be added thru attributes. Like: innerText. So maybe I could make the array an array of properties that I can merge into the 'temp' node?
Thanks in advance!
You could just handle that in a different section just before the for loop like this
for(var elem in div) {
var temp = document.createElement(div[elem].tag);
delete div[elem].tag;
// add the other properties
["innerHtml", "innerText"].forEach(function (attr) {
if(div[ele][attr]) {
temp[attr] = div[ele][attr]
delete div[ele][attr];
});
// add the attributes
for(var prop in div[elem]) {
temp.setAttribute(prop.input[prop]);
}
parentDiv.appendChild(temp);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.