2 * @class Ext.core.DomHelper
3 * <p>The DomHelper class provides a layer of abstraction from DOM and transparently supports creating
4 * elements via DOM or using HTML fragments. It also has the ability to create HTML fragment templates
5 * from your DOM building code.</p>
7 * <p><b><u>DomHelper element specification object</u></b></p>
8 * <p>A specification object is used when creating elements. Attributes of this object
9 * are assumed to be element attributes, except for 4 special attributes:
10 * <div class="mdetail-params"><ul>
11 * <li><b><tt>tag</tt></b> : <div class="sub-desc">The tag name of the element</div></li>
12 * <li><b><tt>children</tt></b> : or <tt>cn</tt><div class="sub-desc">An array of the
13 * same kind of element definition objects to be created and appended. These can be nested
14 * as deep as you want.</div></li>
15 * <li><b><tt>cls</tt></b> : <div class="sub-desc">The class attribute of the element.
16 * This will end up being either the "class" attribute on a HTML fragment or className
17 * for a DOM node, depending on whether DomHelper is using fragments or DOM.</div></li>
18 * <li><b><tt>html</tt></b> : <div class="sub-desc">The innerHTML for the element</div></li>
20 * <p><b>NOTE:</b> For other arbitrary attributes, the value will currently <b>not</b> be automatically
21 * HTML-escaped prior to building the element's HTML string. This means that if your attribute value
22 * contains special characters that would not normally be allowed in a double-quoted attribute value,
23 * you <b>must</b> manually HTML-encode it beforehand (see {@link Ext.String#htmlEncode}) or risk
24 * malformed HTML being created. This behavior may change in a future release.</p>
26 * <p><b><u>Insertion methods</u></b></p>
27 * <p>Commonly used insertion methods:
28 * <div class="mdetail-params"><ul>
29 * <li><b><tt>{@link #append}</tt></b> : <div class="sub-desc"></div></li>
30 * <li><b><tt>{@link #insertBefore}</tt></b> : <div class="sub-desc"></div></li>
31 * <li><b><tt>{@link #insertAfter}</tt></b> : <div class="sub-desc"></div></li>
32 * <li><b><tt>{@link #overwrite}</tt></b> : <div class="sub-desc"></div></li>
33 * <li><b><tt>{@link #createTemplate}</tt></b> : <div class="sub-desc"></div></li>
34 * <li><b><tt>{@link #insertHtml}</tt></b> : <div class="sub-desc"></div></li>
37 * <p><b><u>Example</u></b></p>
38 * <p>This is an example, where an unordered list with 3 children items is appended to an existing
39 * element with id <tt>'my-div'</tt>:<br>
41 var dh = Ext.core.DomHelper; // create shorthand alias
42 // specification object
47 // append children after creating
48 children: [ // may also specify 'cn' instead of 'children'
49 {tag: 'li', id: 'item0', html: 'List Item 0'},
50 {tag: 'li', id: 'item1', html: 'List Item 1'},
51 {tag: 'li', id: 'item2', html: 'List Item 2'}
55 'my-div', // the context element 'my-div' can either be the id or the actual node
56 spec // the specification object
59 * <p>Element creation specification parameters in this class may also be passed as an Array of
60 * specification objects. This can be used to insert multiple sibling nodes into an existing
61 * container very efficiently. For example, to add more list items to the example above:<pre><code>
63 {tag: 'li', id: 'item3', html: 'List Item 3'},
64 {tag: 'li', id: 'item4', html: 'List Item 4'}
68 * <p><b><u>Templating</u></b></p>
69 * <p>The real power is in the built-in templating. Instead of creating or appending any elements,
70 * <tt>{@link #createTemplate}</tt> returns a Template object which can be used over and over to
71 * insert new elements. Revisiting the example above, we could utilize templating this time:
74 var list = dh.append('my-div', {tag: 'ul', cls: 'my-list'});
76 var tpl = dh.createTemplate({tag: 'li', id: 'item{0}', html: 'List Item {0}'});
78 for(var i = 0; i < 5, i++){
79 tpl.append(list, [i]); // use template to append to the actual node
82 * <p>An example using a template:<pre><code>
83 var html = '<a id="{0}" href="{1}" class="nav">{2}</a>';
85 var tpl = new Ext.core.DomHelper.createTemplate(html);
86 tpl.append('blog-roll', ['link1', 'http://www.edspencer.net/', "Ed's Site"]);
87 tpl.append('blog-roll', ['link2', 'http://www.dustindiaz.com/', "Dustin's Site"]);
90 * <p>The same example using named parameters:<pre><code>
91 var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
93 var tpl = new Ext.core.DomHelper.createTemplate(html);
94 tpl.append('blog-roll', {
96 url: 'http://www.edspencer.net/',
99 tpl.append('blog-roll', {
101 url: 'http://www.dustindiaz.com/',
102 text: "Dustin's Site"
106 * <p><b><u>Compiling Templates</u></b></p>
107 * <p>Templates are applied using regular expressions. The performance is great, but if
108 * you are adding a bunch of DOM elements using the same template, you can increase
109 * performance even further by {@link Ext.Template#compile "compiling"} the template.
110 * The way "{@link Ext.Template#compile compile()}" works is the template is parsed and
111 * broken up at the different variable points and a dynamic function is created and eval'ed.
112 * The generated function performs string concatenation of these parts and the passed
113 * variables instead of using regular expressions.
115 var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
117 var tpl = new Ext.core.DomHelper.createTemplate(html);
120 //... use template like normal
123 * <p><b><u>Performance Boost</u></b></p>
124 * <p>DomHelper will transparently create HTML fragments when it can. Using HTML fragments instead
125 * of DOM can significantly boost performance.</p>
126 * <p>Element creation specification parameters may also be strings. If {@link #useDom} is <tt>false</tt>,
127 * then the string is used as innerHTML. If {@link #useDom} is <tt>true</tt>, a string specification
128 * results in the creation of a text node. Usage:</p>
130 Ext.core.DomHelper.useDom = true; // force it to use DOM; reduces performance
135 Ext.core.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,
143 // kill repeat to save bytes
144 afterbegin = 'afterbegin',
145 afterend = 'afterend',
146 beforebegin = 'beforebegin',
147 beforeend = 'beforeend',
156 function doInsert(el, o, returnElement, pos, sibling, append){
160 newNode = createDom(o, null);
162 el.appendChild(newNode);
164 (sibling == 'firstChild' ? el : el.parentNode).insertBefore(newNode, el[sibling] || el);
167 newNode = Ext.core.DomHelper.insertHtml(pos, el, Ext.core.DomHelper.createHtml(o));
169 return returnElement ? Ext.get(newNode, true) : newNode;
172 function createDom(o, parentNode){
180 if (Ext.isArray(o)) { // Allow Arrays of siblings to be inserted
181 el = doc.createDocumentFragment(); // in one shot using a DocumentFragment
182 for (var i = 0, l = o.length; i < l; i++) {
185 } else if (typeof o == 'string') { // Allow a string as a child spec.
186 el = doc.createTextNode(o);
188 el = doc.createElement( o.tag || 'div' );
189 useSet = !!el.setAttribute; // In IE some elements don't have setAttribute
191 if(!confRe.test(attr)){
197 el.setAttribute(attr, val);
204 Ext.core.DomHelper.applyStyles(el, o.style);
206 if ((cn = o.children || o.cn)) {
209 el.innerHTML = o.html;
213 parentNode.appendChild(el);
218 // build as innerHTML where available
219 function createHtml(o){
227 if(typeof o == "string"){
229 } else if (Ext.isArray(o)) {
230 for (i=0; i < o.length; i++) {
232 b += createHtml(o[i]);
236 b += '<' + (o.tag = o.tag || 'div');
239 if(!confRe.test(attr)){
240 if (typeof val == "object") {
241 b += ' ' + attr + '="';
243 b += key + ':' + val[key] + ';';
247 b += ' ' + ({cls : 'class', htmlFor : 'for'}[attr] || attr) + '="' + val + '"';
251 // Now either just close the tag or try to add children and close the tag.
252 if (emptyTags.test(o.tag)) {
256 if ((cn = o.children || o.cn)) {
261 b += '</' + o.tag + '>';
267 function ieTable(depth, s, h, e){
268 tempTableEl.innerHTML = [s, h, e].join('');
275 // If the result is multiple siblings, then encapsulate them into one fragment.
278 var df = document.createDocumentFragment();
291 * Nasty code for IE's broken table implementation
293 function insertIntoTable(tag, where, el, html) {
297 tempTableEl = tempTableEl || document.createElement('div');
299 if(tag == 'td' && (where == afterbegin || where == beforeend) ||
300 !tableElRe.test(tag) && (where == beforebegin || where == afterend)) {
303 before = where == beforebegin ? el :
304 where == afterend ? el.nextSibling :
305 where == afterbegin ? el.firstChild : null;
307 if (where == beforebegin || where == afterend) {
311 if (tag == 'td' || (tag == 'tr' && (where == beforeend || where == afterbegin))) {
312 node = ieTable(4, trs, html, tre);
313 } else if ((tag == 'tbody' && (where == beforeend || where == afterbegin)) ||
314 (tag == 'tr' && (where == beforebegin || where == afterend))) {
315 node = ieTable(3, tbs, html, tbe);
317 node = ieTable(2, ts, html, te);
319 el.insertBefore(node, before);
325 * Fix for IE9 createContextualFragment missing method
327 function createContextualFragment(html){
328 var div = document.createElement("div"),
329 fragment = document.createDocumentFragment(),
333 div.innerHTML = html;
334 childNodes = div.childNodes;
335 length = childNodes.length;
337 for (; i < length; i++) {
338 fragment.appendChild(childNodes[i].cloneNode(true));
346 * Returns the markup for the passed Element(s) config.
347 * @param {Object} o The DOM object spec (and children)
350 markup : function(o){
351 return createHtml(o);
355 * Applies a style specification to an element.
356 * @param {String/HTMLElement} el The element to apply styles to
357 * @param {String/Object/Function} styles A style specification string e.g. 'width:100px', or object in the form {width:'100px'}, or
358 * a function which returns such a specification.
360 applyStyles : function(el, styles){
363 if (typeof styles == "function") {
364 styles = styles.call();
366 if (typeof styles == "string") {
367 styles = Ext.core.Element.parseStyles(styles);
369 if (typeof styles == "object") {
376 * Inserts an HTML fragment into the DOM.
377 * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
378 * @param {HTMLElement/TextNode} el The context element
379 * @param {String} html The HTML fragment
380 * @return {HTMLElement} The new node
382 insertHtml : function(where, el, html){
391 where = where.toLowerCase();
392 // add these here because they are used in both branches of the condition.
393 hash[beforebegin] = ['BeforeBegin', 'previousSibling'];
394 hash[afterend] = ['AfterEnd', 'nextSibling'];
396 // if IE and context element is an HTMLElement
397 if (el.insertAdjacentHTML) {
398 if(tableRe.test(el.tagName) && (rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html))){
402 // add these two to the hash.
403 hash[afterbegin] = ['AfterBegin', 'firstChild'];
404 hash[beforeend] = ['BeforeEnd', 'lastChild'];
405 if ((hashVal = hash[where])) {
406 el.insertAdjacentHTML(hashVal[0], html);
407 return el[hashVal[1]];
409 // if (not IE and context element is an HTMLElement) or TextNode
411 // we cannot insert anything inside a textnode so...
412 if (Ext.isTextNode(el)) {
413 where = where === 'afterbegin' ? 'beforebegin' : where;
414 where = where === 'beforeend' ? 'afterend' : where;
416 range = Ext.supports.CreateContextualFragment ? el.ownerDocument.createRange() : undefined;
417 setStart = 'setStart' + (endRe.test(where) ? 'After' : 'Before');
421 frag = range.createContextualFragment(html);
423 frag = createContextualFragment(html);
425 el.parentNode.insertBefore(frag, where == beforebegin ? el : el.nextSibling);
426 return el[(where == beforebegin ? 'previous' : 'next') + 'Sibling'];
428 rangeEl = (where == afterbegin ? 'first' : 'last') + 'Child';
431 range[setStart](el[rangeEl]);
432 frag = range.createContextualFragment(html);
434 frag = createContextualFragment(html);
437 if(where == afterbegin){
438 el.insertBefore(frag, el.firstChild);
440 el.appendChild(frag);
450 sourceClass: 'Ext.core.DomHelper',
451 sourceMethod: 'insertHtml',
454 msg: 'Illegal insertion point reached: "' + where + '"'
460 * Creates new DOM element(s) and inserts them before el.
461 * @param {Mixed} el The context element
462 * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
463 * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
464 * @return {HTMLElement/Ext.core.Element} The new node
466 insertBefore : function(el, o, returnElement){
467 return doInsert(el, o, returnElement, beforebegin);
471 * Creates new DOM element(s) and inserts them after el.
472 * @param {Mixed} el The context element
473 * @param {Object} o The DOM object spec (and children)
474 * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
475 * @return {HTMLElement/Ext.core.Element} The new node
477 insertAfter : function(el, o, returnElement){
478 return doInsert(el, o, returnElement, afterend, 'nextSibling');
482 * Creates new DOM element(s) and inserts them as the first child of el.
483 * @param {Mixed} el The context element
484 * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
485 * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
486 * @return {HTMLElement/Ext.core.Element} The new node
488 insertFirst : function(el, o, returnElement){
489 return doInsert(el, o, returnElement, afterbegin, 'firstChild');
493 * Creates new DOM element(s) and appends them to el.
494 * @param {Mixed} el The context element
495 * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
496 * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
497 * @return {HTMLElement/Ext.core.Element} The new node
499 append : function(el, o, returnElement){
500 return doInsert(el, o, returnElement, beforeend, '', true);
504 * Creates new DOM element(s) and overwrites the contents of el with them.
505 * @param {Mixed} el The context element
506 * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
507 * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
508 * @return {HTMLElement/Ext.core.Element} The new node
510 overwrite : function(el, o, returnElement){
512 el.innerHTML = createHtml(o);
513 return returnElement ? Ext.get(el.firstChild) : el.firstChild;
516 createHtml : createHtml,
519 * Creates new DOM element(s) without inserting them to the document.
520 * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
521 * @return {HTMLElement} The new uninserted node
524 createDom: createDom,
526 /** True to force the use of DOM instead of html fragments @type Boolean */
530 * Creates a new Ext.Template from the DOM object spec.
531 * @param {Object} o The DOM object spec (and children)
532 * @return {Ext.Template} The new template
534 createTemplate : function(o){
535 var html = Ext.core.DomHelper.createHtml(o);
536 return Ext.create('Ext.Template', html);