[whatwg] createElement convenience method

On 10/20/07, Keryx Web <webmaster at keryx.se> wrote:
> Hello again!
>
> I was putting together a page of exercices for my students. It's in
> Swedish and mirrored at http://gunther.ne.keryx.se/datagrund-ovningar/
>
> This page must work when delivered from the file system so I can't use
> my beloved PHP. However, I missed one feature like crazy. Consider this:
>
> var link_to_add  = document.createElement("a");
> var link_text    = document.createTextNode(the_text.nodeValue);
> link_to_add.appendChild(link_text);
>
> If PHP:s convenience additions to the W3C DOM were made standard (and
> implemented in browsers) it could have been:
>
> var link_to_add  = document.createElement("a",the_text.nodeValue);

You can do this:

Document.prototype.createElement = function (name, text) {
    var el = this.createElementNS("http://www.w3.org/1999/xhtml", name);
    if (text) {
        el.appendChild(this.createTextNode(text));
    }
    return el;
};
(or, even cache the orginal createElement and provide both a new ns
and normal version)

Then, you can use:

var link = document.createElement("a", "zipzambam");
alert(link.textContent);

However, the overriding of createElement only seems to work in Opera.

Instead, you could do:

Document.prototype.createElementWithTextNS = function (ns, name, text) {
    var el = this.createElementNS(ns, name);
    el.appendChild(this.createTextNode(text));
    return el;
};
Document.prototype.createElementWithText = function (name, text) {
    return this.createElementWithTextNS("http://www.w3.org/1999/xhtml",
name, text);
};

and use:

var link = document.createElementWithText("a", "zipzambam");
alert(link.textContent);

or the NS version if you need to.

Of course, when you want text, just a regular wrapper function would
be better for IE's sake:

function createElementWithText(doc, name, text) {
    var el = doc.createElement(name);
    el.appendChild(doc.createTextNode(text));
    return el;
}
var link = createElementWithText(document, "a", "zipzambam");
alert(link.innerHTML);

Or, you could do it this way:

function createElement(doc, name, text) {
    var el = doc.createElement(name);
    if (text) {
        el.appendChild(doc.createTextNode(text));
    }
    return el;
}
var link = createElement(document, "a", "zipzambam");
alert(link.innerHTML);

and use it for both creating elements and elements with text.

-- 
Michael

Received on Monday, 22 October 2007 02:14:15 UTC