DOMUtil

Working with DOM nodes is a pain. Code using document.createElement tends to be incredibly verbose and just not much fun.

Prototype provides some convenient shortcuts for creating DOM nodes:


var a = new Element("a", { "class": "foo", href: "/foo.html" }).update("Next page");

The only problem here is if you are interacting with a bbq GUIWidget.


var button = new bbq.gui.button.GUIButton({text: "Next page", onClick: function() {
    // some code here
}});

var div = new Element("div", { "class": "foo" });

// kaboom!
div.update(button);

// kaboom!
div.appendChild(button);

Enter DOMUtil. This class has some utility methods which know the difference between GUIWidgets DOM nodes and strings so it's safe to pass anything in.

DOMUtil#createElement

The first argument to DOMUtil#createElement is the name of the element you wish to create as a string. The last argument is a key/value object that will be applied to the returned element as attributes. If you pass three arguments, the second argument becomes the contents of the element. This can be a string, a GUIWidget, a node or an array containing any combination of the three.


var button = new bbq.gui.button.GUIButton({text: "Next page", onClick: function() {
    // some code here
}});

// the button above is the contents of the div
var div = DOMUtil.createElement("div", button, { className: "foo" });

// This time include an instruction as well
var div2 = DOMUtil.createElement("div", ["Click this: ", button], { className: "foo" });

Alternatively, with a DOM Node and a GUIWidget passed in:


var button = new bbq.gui.button.GUIButton({text: "Next page", onClick: function() {
    // some code here
}});

var div = DOMUtil.createElement("div", [
    DOMUtil.createElement("label", "Click this:"),
    button
], { className: "foo", "style": {"border": "1px solid #F10"} });

DOMUtil#emptyNode

DOMUtil#emptyNode takes a Node/GUIWidget as an argument and removes all of it's children.


// create node that has markup <span>foo</span>
var node = DOMUtil.createElement("span", "foo");

DOMUtil.emptyNode(node);

// node is now <span></span>

DOMUtil#isInDOM

DOMUtil#isInDom returns true if the passed node is in the DOM, false otherwise.


// create node that has markup foo
var node = DOMUtil.createElement("span", "foo");

// false
DOMUtil.isInDom(node);

// add it to the DOM
document.body.appendChild(node);

// true
DOMUtil.isInDOM(node);

See the JSDocs for further discussion.