Reputation: 2230
In order to write XML, HTML or any other tree-like structures I once made a small DOM-like, python library with two main functions defined as such :
grow(parent_instance, child_tag)
which returns the newly created and appended child_instance
attach(parent_instance, text)
which append the text and returns the parent_instance
Writing trees became a breeze.
Newbie in javascript, (finding $('<div></div>')
ugly) I tried to implement this again, on top of DOM, and jquery... Am I re-inventing the wheel ? How could it be more javascriptic ?
function grow(parent, tagName) {
var node = $(document.createElement(tagName));
parent.append(node);
return node;
}
edit @AmmarCSE :
yuck >_< I start to understand why I still got an error with .appendChild()
in your first example... grow()
is called first with a jQuery selected parent (which use .append()
) and return a classic DOM object, (which use .appendChild()
).
I have to find a way to keep nestability :)
Upvotes: 1
Views: 108
Reputation: 2230
I found my perfect answer, so I share it.
$.fn.grow = function (name) {
var child = $(document.createElement(name));
this.append(child);
return child;
};
It adds a jQuery method and enable this kind of procedural tree building:
var ord_list = ["first", "second", "third"];
var n_table = $('#ordinals')
for (var i=0 ; i < ord_list.length ; i++) {
n_tr = n_table.grow('tr');
n_td = n_tr.grow('td');
n_td.text(i);
n_td = n_tr.grow('td');
n_td.text(ord_list[i]);
}
which produces:
<table>
<tr><td>1</td><td>first</td></tr>
<tr><td>2</td><td>second</td></tr>
<tr><td>3</td><td>third</td></tr>
</table>
clean, unobtrusive, I will propose it to jQuery devs :D
.attach() is useless since .text() already exists (thx @AmmarCSE)
Upvotes: 0
Reputation: 30607
Its not about re-inventing the wheel or being more 'javascriptic'. You simply have many options to achieve the same goal.
Javascript:
function grow(parent, tagName) {
var node = document.createElement(tagName);
//notice, the jQuery wrapper was removed as it is not needed
parent.appendChild(node);
return node;
}
function attach(parent_instance, text) {
parent_instance.innerHTML = text;
return parent_instance;
}
jQuery:
function grow(parent, tagName) {
return $(parent).append($(document.createElement(tagName)));
}
function attach(parent_instance, text) {
return $(parent_instance).text(text);
}
Upvotes: 1