If you ever had to write JavaScript and you had to write something like this in JavaScript:
var p = document.createElement ("p");
p.appendChild (document.createTextNode (“Real Fish Fish."));
var div = document.createElement ("div");
div.setAttribute ('id', 'new');
div.appendChild (p);
then it may be useful to you.
Problem: when you create more than one element nested in each other, the code becomes very complex.
I propose a simple tool for solving the problem - the function create () (source below). For example, create a paragraph of text:
var el = create ("p", {}, "Farewell, Love!");
Or a div with a paragraph and a link inside it:
var div = create ("div", {id: "new", style: "background: #fff"},
create ("p", {align: 'center'},
"introduction: ",
create ('a', {href: " ua.fishki.net/picso/kotdavinchi.jpg "},
"Picture"),
": end" )
);
Or, we make a table:
var holder = document.getElementById ("holder2");
var table;
var td;
holder.appendChild (
table =
create ("table", {id: 'ugly', cols: 3},
create ("tbody", {},
create ("tr", {},
create ("td", {width: '10% '},
"Hello"),
td =
create ("td", {style: 'background: #fcc'},
"There"),
create ("td", {Class: 'special2'}, "everywhere")
)
)
)
);
Note:
1. IE requires tbody element, otherwise refuses to show the table.
2. The class attribute conflicts with something, so you have to write it as Class. It seems that this effect has no effect.
3. table = and tr = in the example allow you to save the created nested objects for further work with them.
4. This code works in IE, Mozilla, and Opera.
Function itself
function create (name, attributes) {
var el = document.createElement (name);
if (typeof attributes == 'object') {
for (var i in attributes) {
el.setAttribute (i, attributes [i]);
')
if (i.toLowerCase () == 'class') {
el.className = attributes [i]; // for IE compatibility
} else if (i.toLowerCase () == 'style') {
el.style.cssText = attributes [i]; // for IE compatibility
}
}
}
for (var i = 2; i <arguments.length; i ++) {
var val = arguments [i];
if (typeof val == 'string') {val = document.createTextNode (val)};
el.appendChild (val);
}
return el;
}
For the idea should thank Ivan Kurmanov,
Original article with working examples:
ahinea.com/2006/04/14/javascript-dom-create