YUI 3, Dynamic DOM Search Experiment

Todays article illustrates an experimental function that parses a string, containing instructions for searching the DOM relative to a node. This method was inspired by a desire to allow a separate design team to specify the relative location of other DOM nodes. This way, parts of the JavaScript that handle user triggered events (such as click) need not hardcode relative nodes.

For example, suppose when the user clicks on an anchor, a relative node is made visible and the design team frequently changes the location of that node. An ID could be used, but that doesnt work as well with dynamically generated content, instead the following method might be useful:

Example 1: Exec Function

YAHOO.util.Dom.exec = function(elem, instructions) {
	var node = YAHOO.util.Dom.get(elem);
	if (! (node && instructions)) {return;}
	var _s = instructions.split(.);
	for (var i = 0; i < _s.length; i += 1) {
		if (node) {
			var task = _s[i];
			if ($D[task]) {
				node = $D[task](node);
			} // todo: support childNodes[]
			else if (node[task]) {
				node = node[task];
			else {
				// unsupported technique
		else {
			return true;
	return node;

The exec method requires two parameters: the target node, and a string containing instructions for finding a node relative to the target. When both parameters are provided, the instructions string is split around period (.), creating an array of instructions to iterate on. YUI Dom methods and/or regular DOM methods may be used (as long as they dont require brackets), such as the following: "parentNode.nextSibling.getFirstChild" (will execute the following "YAHOO.util.Dom.getFirstChild(node.parentNode.nextSibling)"). Lastly, exec returns undefined when a node is not found.

While, this method is useful, it is lacking a lot of features such as searching by class/tag name or children nodes. Libraries such as YUI 3 and jQuery have optimized DOM searching methods, which could be leveraged by this method. The reason I didnt use these methods is that they only search down the DOM tree and not up, which I needed. Although there probably is an extension out there for this, but a quick search didnt find it and what I have worked to meet my immediate needs. Next week, I will show a technique for dynamically attaching blind animations to the DOM that uses this method to relatively reference the node to animate from the triggering anchor.