3 * Copyright(c) 2006-2010 Ext JS, Inc.
5 * http://www.extjs.com/license
9 * <p>The DomHelper class provides a layer of abstraction from DOM and transparently supports creating
10 * elements via DOM or using HTML fragments. It also has the ability to create HTML fragment templates
11 * from your DOM building code.</p>
13 * <p><b><u>DomHelper element specification object</u></b></p>
14 * <p>A specification object is used when creating elements. Attributes of this object
15 * are assumed to be element attributes, except for 4 special attributes:
16 * <div class="mdetail-params"><ul>
17 * <li><b><tt>tag</tt></b> : <div class="sub-desc">The tag name of the element</div></li>
18 * <li><b><tt>children</tt></b> : or <tt>cn</tt><div class="sub-desc">An array of the
19 * same kind of element definition objects to be created and appended. These can be nested
20 * as deep as you want.</div></li>
21 * <li><b><tt>cls</tt></b> : <div class="sub-desc">The class attribute of the element.
22 * This will end up being either the "class" attribute on a HTML fragment or className
23 * for a DOM node, depending on whether DomHelper is using fragments or DOM.</div></li>
24 * <li><b><tt>html</tt></b> : <div class="sub-desc">The innerHTML for the element</div></li>
27 * <p><b><u>Insertion methods</u></b></p>
28 * <p>Commonly used insertion methods:
29 * <div class="mdetail-params"><ul>
30 * <li><b><tt>{@link #append}</tt></b> : <div class="sub-desc"></div></li>
31 * <li><b><tt>{@link #insertBefore}</tt></b> : <div class="sub-desc"></div></li>
32 * <li><b><tt>{@link #insertAfter}</tt></b> : <div class="sub-desc"></div></li>
33 * <li><b><tt>{@link #overwrite}</tt></b> : <div class="sub-desc"></div></li>
34 * <li><b><tt>{@link #createTemplate}</tt></b> : <div class="sub-desc"></div></li>
35 * <li><b><tt>{@link #insertHtml}</tt></b> : <div class="sub-desc"></div></li>
38 * <p><b><u>Example</u></b></p>
39 * <p>This is an example, where an unordered list with 3 children items is appended to an existing
40 * element with id <tt>'my-div'</tt>:<br>
42 var dh = Ext.DomHelper; // create shorthand alias
43 // specification object
48 // append children after creating
49 children: [ // may also specify 'cn' instead of 'children'
50 {tag: 'li', id: 'item0', html: 'List Item 0'},
51 {tag: 'li', id: 'item1', html: 'List Item 1'},
52 {tag: 'li', id: 'item2', html: 'List Item 2'}
56 'my-div', // the context element 'my-div' can either be the id or the actual node
57 spec // the specification object
60 * <p>Element creation specification parameters in this class may also be passed as an Array of
61 * specification objects. This can be used to insert multiple sibling nodes into an existing
62 * container very efficiently. For example, to add more list items to the example above:<pre><code>
64 {tag: 'li', id: 'item3', html: 'List Item 3'},
65 {tag: 'li', id: 'item4', html: 'List Item 4'}
69 * <p><b><u>Templating</u></b></p>
70 * <p>The real power is in the built-in templating. Instead of creating or appending any elements,
71 * <tt>{@link #createTemplate}</tt> returns a Template object which can be used over and over to
72 * insert new elements. Revisiting the example above, we could utilize templating this time:
75 var list = dh.append('my-div', {tag: 'ul', cls: 'my-list'});
77 var tpl = dh.createTemplate({tag: 'li', id: 'item{0}', html: 'List Item {0}'});
79 for(var i = 0; i < 5, i++){
80 tpl.append(list, [i]); // use template to append to the actual node
83 * <p>An example using a template:<pre><code>
84 var html = '<a id="{0}" href="{1}" class="nav">{2}</a>';
86 var tpl = new Ext.DomHelper.createTemplate(html);
87 tpl.append('blog-roll', ['link1', 'http://www.jackslocum.com/', "Jack's Site"]);
88 tpl.append('blog-roll', ['link2', 'http://www.dustindiaz.com/', "Dustin's Site"]);
91 * <p>The same example using named parameters:<pre><code>
92 var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
94 var tpl = new Ext.DomHelper.createTemplate(html);
95 tpl.append('blog-roll', {
97 url: 'http://www.jackslocum.com/',
98 text: "Jack's Site"
100 tpl.append('blog-roll', {
102 url: 'http://www.dustindiaz.com/',
103 text: "Dustin's Site"
107 * <p><b><u>Compiling Templates</u></b></p>
108 * <p>Templates are applied using regular expressions. The performance is great, but if
109 * you are adding a bunch of DOM elements using the same template, you can increase
110 * performance even further by {@link Ext.Template#compile "compiling"} the template.
111 * The way "{@link Ext.Template#compile compile()}" works is the template is parsed and
112 * broken up at the different variable points and a dynamic function is created and eval'ed.
113 * The generated function performs string concatenation of these parts and the passed
114 * variables instead of using regular expressions.
116 var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
118 var tpl = new Ext.DomHelper.createTemplate(html);
121 //... use template like normal
124 * <p><b><u>Performance Boost</u></b></p>
125 * <p>DomHelper will transparently create HTML fragments when it can. Using HTML fragments instead
126 * of DOM can significantly boost performance.</p>
127 * <p>Element creation specification parameters may also be strings. If {@link #useDom} is <tt>false</tt>,
128 * then the string is used as innerHTML. If {@link #useDom} is <tt>true</tt>, a string specification
129 * results in the creation of a text node. Usage:</p>
131 Ext.DomHelper.useDom = true; // force it to use DOM; reduces performance
135 Ext.DomHelper = function(){
136 var tempTableEl = null,
137 emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i,
138 tableRe = /^table|tbody|tr|td$/i,
139 confRe = /tag|children|cn|html$/i,
140 tableElRe = /td|tr|tbody/i,
141 cssRe = /([a-z0-9-]+)\s*:\s*([^;\s]+(?:\s*[^;\s]+)*);?/gi,
144 // kill repeat to save bytes
145 afterbegin = 'afterbegin',
146 afterend = 'afterend',
147 beforebegin = 'beforebegin',
148 beforeend = 'beforeend',
157 function doInsert(el, o, returnElement, pos, sibling, append){
158 var newNode = pub.insertHtml(pos, Ext.getDom(el), createHtml(o));
159 return returnElement ? Ext.get(newNode, true) : newNode;
162 // build as innerHTML where available
163 function createHtml(o){
171 if(typeof o == "string"){
173 } else if (Ext.isArray(o)) {
174 for (var i=0; i < o.length; i++) {
176 b += createHtml(o[i]);
180 b += '<' + (o.tag = o.tag || 'div');
183 if(!confRe.test(attr)){
184 if (typeof val == "object") {
185 b += ' ' + attr + '="';
187 b += key + ':' + val[key] + ';';
191 b += ' ' + ({cls : 'class', htmlFor : 'for'}[attr] || attr) + '="' + val + '"';
195 // Now either just close the tag or try to add children and close the tag.
196 if (emptyTags.test(o.tag)) {
200 if ((cn = o.children || o.cn)) {
205 b += '</' + o.tag + '>';
211 function ieTable(depth, s, h, e){
212 tempTableEl.innerHTML = [s, h, e].join('');
219 // If the result is multiple siblings, then encapsulate them into one fragment.
220 if(ns = el.nextSibling){
221 var df = document.createDocumentFragment();
234 * Nasty code for IE's broken table implementation
236 function insertIntoTable(tag, where, el, html) {
240 tempTableEl = tempTableEl || document.createElement('div');
242 if(tag == 'td' && (where == afterbegin || where == beforeend) ||
243 !tableElRe.test(tag) && (where == beforebegin || where == afterend)) {
246 before = where == beforebegin ? el :
247 where == afterend ? el.nextSibling :
248 where == afterbegin ? el.firstChild : null;
250 if (where == beforebegin || where == afterend) {
254 if (tag == 'td' || (tag == 'tr' && (where == beforeend || where == afterbegin))) {
255 node = ieTable(4, trs, html, tre);
256 } else if ((tag == 'tbody' && (where == beforeend || where == afterbegin)) ||
257 (tag == 'tr' && (where == beforebegin || where == afterend))) {
258 node = ieTable(3, tbs, html, tbe);
260 node = ieTable(2, ts, html, te);
262 el.insertBefore(node, before);
269 * Returns the markup for the passed Element(s) config.
270 * @param {Object} o The DOM object spec (and children)
273 markup : function(o){
274 return createHtml(o);
278 * Applies a style specification to an element.
279 * @param {String/HTMLElement} el The element to apply styles to
280 * @param {String/Object/Function} styles A style specification string e.g. 'width:100px', or object in the form {width:'100px'}, or
281 * a function which returns such a specification.
283 applyStyles : function(el, styles){
291 if(typeof styles == "function"){
292 styles = styles.call();
294 if(typeof styles == "string"){
295 while((matches = cssRe.exec(styles))){
296 el.setStyle(matches[1], matches[2]);
298 }else if (typeof styles == "object"){
305 * Inserts an HTML fragment into the DOM.
306 * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
307 * @param {HTMLElement} el The context element
308 * @param {String} html The HTML fragment
309 * @return {HTMLElement} The new node
311 insertHtml : function(where, el, html){
320 where = where.toLowerCase();
321 // add these here because they are used in both branches of the condition.
322 hash[beforebegin] = ['BeforeBegin', 'previousSibling'];
323 hash[afterend] = ['AfterEnd', 'nextSibling'];
325 if (el.insertAdjacentHTML) {
326 if(tableRe.test(el.tagName) && (rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html))){
329 // add these two to the hash.
330 hash[afterbegin] = ['AfterBegin', 'firstChild'];
331 hash[beforeend] = ['BeforeEnd', 'lastChild'];
332 if ((hashVal = hash[where])) {
333 el.insertAdjacentHTML(hashVal[0], html);
334 return el[hashVal[1]];
337 range = el.ownerDocument.createRange();
338 setStart = 'setStart' + (endRe.test(where) ? 'After' : 'Before');
341 frag = range.createContextualFragment(html);
342 el.parentNode.insertBefore(frag, where == beforebegin ? el : el.nextSibling);
343 return el[(where == beforebegin ? 'previous' : 'next') + 'Sibling'];
345 rangeEl = (where == afterbegin ? 'first' : 'last') + 'Child';
347 range[setStart](el[rangeEl]);
348 frag = range.createContextualFragment(html);
349 if(where == afterbegin){
350 el.insertBefore(frag, el.firstChild);
352 el.appendChild(frag);
360 throw 'Illegal insertion point -> "' + where + '"';
364 * Creates new DOM element(s) and inserts them before el.
365 * @param {Mixed} el The context element
366 * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
367 * @param {Boolean} returnElement (optional) true to return a Ext.Element
368 * @return {HTMLElement/Ext.Element} The new node
370 insertBefore : function(el, o, returnElement){
371 return doInsert(el, o, returnElement, beforebegin);
375 * Creates new DOM element(s) and inserts them after el.
376 * @param {Mixed} el The context element
377 * @param {Object} o The DOM object spec (and children)
378 * @param {Boolean} returnElement (optional) true to return a Ext.Element
379 * @return {HTMLElement/Ext.Element} The new node
381 insertAfter : function(el, o, returnElement){
382 return doInsert(el, o, returnElement, afterend, 'nextSibling');
386 * Creates new DOM element(s) and inserts them as the first child of el.
387 * @param {Mixed} el The context element
388 * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
389 * @param {Boolean} returnElement (optional) true to return a Ext.Element
390 * @return {HTMLElement/Ext.Element} The new node
392 insertFirst : function(el, o, returnElement){
393 return doInsert(el, o, returnElement, afterbegin, 'firstChild');
397 * Creates new DOM element(s) and appends them to el.
398 * @param {Mixed} el The context element
399 * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
400 * @param {Boolean} returnElement (optional) true to return a Ext.Element
401 * @return {HTMLElement/Ext.Element} The new node
403 append : function(el, o, returnElement){
404 return doInsert(el, o, returnElement, beforeend, '', true);
408 * Creates new DOM element(s) and overwrites the contents of el with them.
409 * @param {Mixed} el The context element
410 * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
411 * @param {Boolean} returnElement (optional) true to return a Ext.Element
412 * @return {HTMLElement/Ext.Element} The new node
414 overwrite : function(el, o, returnElement){
416 el.innerHTML = createHtml(o);
417 return returnElement ? Ext.get(el.firstChild) : el.firstChild;
420 createHtml : createHtml