4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>The source code</title>
6 <link href="../prettify/prettify.css" type="text/css" rel="stylesheet" />
7 <script type="text/javascript" src="../prettify/prettify.js"></script>
8 <style type="text/css">
9 .highlight { display: block; background-color: #ddd; }
11 <script type="text/javascript">
12 function highlight() {
13 document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
17 <body onload="prettyPrint(); highlight();">
18 <pre class="prettyprint lang-js"><span id='Ext-core-DomHelper'>/**
19 </span> * @class Ext.core.DomHelper
20 * <p>The DomHelper class provides a layer of abstraction from DOM and transparently supports creating
21 * elements via DOM or using HTML fragments. It also has the ability to create HTML fragment templates
22 * from your DOM building code.</p>
24 * <p><b><u>DomHelper element specification object</u></b></p>
25 * <p>A specification object is used when creating elements. Attributes of this object
26 * are assumed to be element attributes, except for 4 special attributes:
27 * <div class="mdetail-params"><ul>
28 * <li><b><tt>tag</tt></b> : <div class="sub-desc">The tag name of the element</div></li>
29 * <li><b><tt>children</tt></b> : or <tt>cn</tt><div class="sub-desc">An array of the
30 * same kind of element definition objects to be created and appended. These can be nested
31 * as deep as you want.</div></li>
32 * <li><b><tt>cls</tt></b> : <div class="sub-desc">The class attribute of the element.
33 * This will end up being either the "class" attribute on a HTML fragment or className
34 * for a DOM node, depending on whether DomHelper is using fragments or DOM.</div></li>
35 * <li><b><tt>html</tt></b> : <div class="sub-desc">The innerHTML for the element</div></li>
36 * </ul></div></p>
37 * <p><b>NOTE:</b> For other arbitrary attributes, the value will currently <b>not</b> be automatically
38 * HTML-escaped prior to building the element's HTML string. This means that if your attribute value
39 * contains special characters that would not normally be allowed in a double-quoted attribute value,
40 * you <b>must</b> manually HTML-encode it beforehand (see {@link Ext.String#htmlEncode}) or risk
41 * malformed HTML being created. This behavior may change in a future release.</p>
43 * <p><b><u>Insertion methods</u></b></p>
44 * <p>Commonly used insertion methods:
45 * <div class="mdetail-params"><ul>
46 * <li><b><tt>{@link #append}</tt></b> : <div class="sub-desc"></div></li>
47 * <li><b><tt>{@link #insertBefore}</tt></b> : <div class="sub-desc"></div></li>
48 * <li><b><tt>{@link #insertAfter}</tt></b> : <div class="sub-desc"></div></li>
49 * <li><b><tt>{@link #overwrite}</tt></b> : <div class="sub-desc"></div></li>
50 * <li><b><tt>{@link #createTemplate}</tt></b> : <div class="sub-desc"></div></li>
51 * <li><b><tt>{@link #insertHtml}</tt></b> : <div class="sub-desc"></div></li>
52 * </ul></div></p>
54 * <p><b><u>Example</u></b></p>
55 * <p>This is an example, where an unordered list with 3 children items is appended to an existing
56 * element with id <tt>'my-div'</tt>:<br>
57 <pre><code>
58 var dh = Ext.core.DomHelper; // create shorthand alias
59 // specification object
64 // append children after creating
65 children: [ // may also specify 'cn' instead of 'children'
66 {tag: 'li', id: 'item0', html: 'List Item 0'},
67 {tag: 'li', id: 'item1', html: 'List Item 1'},
68 {tag: 'li', id: 'item2', html: 'List Item 2'}
72 'my-div', // the context element 'my-div' can either be the id or the actual node
73 spec // the specification object
75 </code></pre></p>
76 * <p>Element creation specification parameters in this class may also be passed as an Array of
77 * specification objects. This can be used to insert multiple sibling nodes into an existing
78 * container very efficiently. For example, to add more list items to the example above:<pre><code>
80 {tag: 'li', id: 'item3', html: 'List Item 3'},
81 {tag: 'li', id: 'item4', html: 'List Item 4'}
83 * </code></pre></p>
85 * <p><b><u>Templating</u></b></p>
86 * <p>The real power is in the built-in templating. Instead of creating or appending any elements,
87 * <tt>{@link #createTemplate}</tt> returns a Template object which can be used over and over to
88 * insert new elements. Revisiting the example above, we could utilize templating this time:
89 * <pre><code>
91 var list = dh.append('my-div', {tag: 'ul', cls: 'my-list'});
93 var tpl = dh.createTemplate({tag: 'li', id: 'item{0}', html: 'List Item {0}'});
95 for(var i = 0; i < 5, i++){
96 tpl.append(list, [i]); // use template to append to the actual node
98 * </code></pre></p>
99 * <p>An example using a template:<pre><code>
100 var html = '<a id="{0}" href="{1}" class="nav">{2}</a>';
102 var tpl = new Ext.core.DomHelper.createTemplate(html);
103 tpl.append('blog-roll', ['link1', 'http://www.edspencer.net/', "Ed&#39;s Site"]);
104 tpl.append('blog-roll', ['link2', 'http://www.dustindiaz.com/', "Dustin&#39;s Site"]);
105 * </code></pre></p>
107 * <p>The same example using named parameters:<pre><code>
108 var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
110 var tpl = new Ext.core.DomHelper.createTemplate(html);
111 tpl.append('blog-roll', {
113 url: 'http://www.edspencer.net/',
114 text: "Ed&#39;s Site"
116 tpl.append('blog-roll', {
118 url: 'http://www.dustindiaz.com/',
119 text: "Dustin&#39;s Site"
121 * </code></pre></p>
123 * <p><b><u>Compiling Templates</u></b></p>
124 * <p>Templates are applied using regular expressions. The performance is great, but if
125 * you are adding a bunch of DOM elements using the same template, you can increase
126 * performance even further by {@link Ext.Template#compile "compiling"} the template.
127 * The way "{@link Ext.Template#compile compile()}" works is the template is parsed and
128 * broken up at the different variable points and a dynamic function is created and eval'ed.
129 * The generated function performs string concatenation of these parts and the passed
130 * variables instead of using regular expressions.
131 * <pre><code>
132 var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
134 var tpl = new Ext.core.DomHelper.createTemplate(html);
137 //... use template like normal
138 * </code></pre></p>
140 * <p><b><u>Performance Boost</u></b></p>
141 * <p>DomHelper will transparently create HTML fragments when it can. Using HTML fragments instead
142 * of DOM can significantly boost performance.</p>
143 * <p>Element creation specification parameters may also be strings. If {@link #useDom} is <tt>false</tt>,
144 * then the string is used as innerHTML. If {@link #useDom} is <tt>true</tt>, a string specification
145 * results in the creation of a text node. Usage:</p>
146 * <pre><code>
147 Ext.core.DomHelper.useDom = true; // force it to use DOM; reduces performance
148 * </code></pre>
152 Ext.core.DomHelper = function(){
153 var tempTableEl = null,
154 emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i,
155 tableRe = /^table|tbody|tr|td$/i,
156 confRe = /tag|children|cn|html$/i,
157 tableElRe = /td|tr|tbody/i,
160 // kill repeat to save bytes
161 afterbegin = 'afterbegin',
162 afterend = 'afterend',
163 beforebegin = 'beforebegin',
164 beforeend = 'beforeend',
165 ts = '<table>',
166 te = '</table>',
167 tbs = ts+'<tbody>',
168 tbe = '</tbody>'+te,
169 trs = tbs + '<tr>',
170 tre = '</tr>'+tbe;
173 function doInsert(el, o, returnElement, pos, sibling, append){
177 newNode = createDom(o, null);
179 el.appendChild(newNode);
181 (sibling == 'firstChild' ? el : el.parentNode).insertBefore(newNode, el[sibling] || el);
184 newNode = Ext.core.DomHelper.insertHtml(pos, el, Ext.core.DomHelper.createHtml(o));
186 return returnElement ? Ext.get(newNode, true) : newNode;
189 function createDom(o, parentNode){
197 if (Ext.isArray(o)) { // Allow Arrays of siblings to be inserted
198 el = doc.createDocumentFragment(); // in one shot using a DocumentFragment
199 for (var i = 0, l = o.length; i < l; i++) {
202 } else if (typeof o == 'string') { // Allow a string as a child spec.
203 el = doc.createTextNode(o);
205 el = doc.createElement( o.tag || 'div' );
206 useSet = !!el.setAttribute; // In IE some elements don't have setAttribute
208 if(!confRe.test(attr)){
214 el.setAttribute(attr, val);
221 Ext.core.DomHelper.applyStyles(el, o.style);
223 if ((cn = o.children || o.cn)) {
226 el.innerHTML = o.html;
230 parentNode.appendChild(el);
235 // build as innerHTML where available
236 function createHtml(o){
244 if(typeof o == "string"){
246 } else if (Ext.isArray(o)) {
247 for (i=0; i < o.length; i++) {
249 b += createHtml(o[i]);
253 b += '<' + (o.tag = o.tag || 'div');
256 if(!confRe.test(attr)){
257 if (typeof val == "object") {
258 b += ' ' + attr + '="';
260 b += key + ':' + val[key] + ';';
264 b += ' ' + ({cls : 'class', htmlFor : 'for'}[attr] || attr) + '="' + val + '"';
268 // Now either just close the tag or try to add children and close the tag.
269 if (emptyTags.test(o.tag)) {
273 if ((cn = o.children || o.cn)) {
278 b += '</' + o.tag + '>';
284 function ieTable(depth, s, h, e){
285 tempTableEl.innerHTML = [s, h, e].join('');
289 while(++i < depth){
292 // If the result is multiple siblings, then encapsulate them into one fragment.
295 var df = document.createDocumentFragment();
306 <span id='Ext-core-DomHelper-method-insertIntoTable'> /**
308 * Nasty code for IE's broken table implementation
310 function insertIntoTable(tag, where, el, html) {
314 tempTableEl = tempTableEl || document.createElement('div');
316 if(tag == 'td' && (where == afterbegin || where == beforeend) ||
317 !tableElRe.test(tag) && (where == beforebegin || where == afterend)) {
320 before = where == beforebegin ? el :
321 where == afterend ? el.nextSibling :
322 where == afterbegin ? el.firstChild : null;
324 if (where == beforebegin || where == afterend) {
328 if (tag == 'td' || (tag == 'tr' && (where == beforeend || where == afterbegin))) {
329 node = ieTable(4, trs, html, tre);
330 } else if ((tag == 'tbody' && (where == beforeend || where == afterbegin)) ||
331 (tag == 'tr' && (where == beforebegin || where == afterend))) {
332 node = ieTable(3, tbs, html, tbe);
334 node = ieTable(2, ts, html, te);
336 el.insertBefore(node, before);
340 <span id='Ext-core-DomHelper-method-createContextualFragment'> /**
342 * Fix for IE9 createContextualFragment missing method
344 function createContextualFragment(html){
345 var div = document.createElement("div"),
346 fragment = document.createDocumentFragment(),
350 div.innerHTML = html;
351 childNodes = div.childNodes;
352 length = childNodes.length;
354 for (; i < length; i++) {
355 fragment.appendChild(childNodes[i].cloneNode(true));
362 <span id='Ext-core-DomHelper-method-markup'> /**
363 </span> * Returns the markup for the passed Element(s) config.
364 * @param {Object} o The DOM object spec (and children)
367 markup : function(o){
368 return createHtml(o);
371 <span id='Ext-core-DomHelper-method-applyStyles'> /**
372 </span> * Applies a style specification to an element.
373 * @param {String/HTMLElement} el The element to apply styles to
374 * @param {String/Object/Function} styles A style specification string e.g. 'width:100px', or object in the form {width:'100px'}, or
375 * a function which returns such a specification.
377 applyStyles : function(el, styles){
380 if (typeof styles == "function") {
381 styles = styles.call();
383 if (typeof styles == "string") {
384 styles = Ext.core.Element.parseStyles(styles);
386 if (typeof styles == "object") {
392 <span id='Ext-core-DomHelper-method-insertHtml'> /**
393 </span> * Inserts an HTML fragment into the DOM.
394 * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
395 * @param {HTMLElement/TextNode} el The context element
396 * @param {String} html The HTML fragment
397 * @return {HTMLElement} The new node
399 insertHtml : function(where, el, html){
408 where = where.toLowerCase();
409 // add these here because they are used in both branches of the condition.
410 hash[beforebegin] = ['BeforeBegin', 'previousSibling'];
411 hash[afterend] = ['AfterEnd', 'nextSibling'];
413 // if IE and context element is an HTMLElement
414 if (el.insertAdjacentHTML) {
415 if(tableRe.test(el.tagName) && (rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html))){
419 // add these two to the hash.
420 hash[afterbegin] = ['AfterBegin', 'firstChild'];
421 hash[beforeend] = ['BeforeEnd', 'lastChild'];
422 if ((hashVal = hash[where])) {
423 el.insertAdjacentHTML(hashVal[0], html);
424 return el[hashVal[1]];
426 // if (not IE and context element is an HTMLElement) or TextNode
428 // we cannot insert anything inside a textnode so...
429 if (Ext.isTextNode(el)) {
430 where = where === 'afterbegin' ? 'beforebegin' : where;
431 where = where === 'beforeend' ? 'afterend' : where;
433 range = Ext.supports.CreateContextualFragment ? el.ownerDocument.createRange() : undefined;
434 setStart = 'setStart' + (endRe.test(where) ? 'After' : 'Before');
438 frag = range.createContextualFragment(html);
440 frag = createContextualFragment(html);
442 el.parentNode.insertBefore(frag, where == beforebegin ? el : el.nextSibling);
443 return el[(where == beforebegin ? 'previous' : 'next') + 'Sibling'];
445 rangeEl = (where == afterbegin ? 'first' : 'last') + 'Child';
448 range[setStart](el[rangeEl]);
449 frag = range.createContextualFragment(html);
451 frag = createContextualFragment(html);
454 if(where == afterbegin){
455 el.insertBefore(frag, el.firstChild);
457 el.appendChild(frag);
467 sourceClass: 'Ext.core.DomHelper',
468 sourceMethod: 'insertHtml',
471 msg: 'Illegal insertion point reached: "' + where + '"'
476 <span id='Ext-core-DomHelper-method-insertBefore'> /**
477 </span> * Creates new DOM element(s) and inserts them before el.
478 * @param {Mixed} el The context element
479 * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
480 * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
481 * @return {HTMLElement/Ext.core.Element} The new node
483 insertBefore : function(el, o, returnElement){
484 return doInsert(el, o, returnElement, beforebegin);
487 <span id='Ext-core-DomHelper-method-insertAfter'> /**
488 </span> * Creates new DOM element(s) and inserts them after el.
489 * @param {Mixed} el The context element
490 * @param {Object} o The DOM object spec (and children)
491 * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
492 * @return {HTMLElement/Ext.core.Element} The new node
494 insertAfter : function(el, o, returnElement){
495 return doInsert(el, o, returnElement, afterend, 'nextSibling');
498 <span id='Ext-core-DomHelper-method-insertFirst'> /**
499 </span> * Creates new DOM element(s) and inserts them as the first child of el.
500 * @param {Mixed} el The context element
501 * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
502 * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
503 * @return {HTMLElement/Ext.core.Element} The new node
505 insertFirst : function(el, o, returnElement){
506 return doInsert(el, o, returnElement, afterbegin, 'firstChild');
509 <span id='Ext-core-DomHelper-method-append'> /**
510 </span> * Creates new DOM element(s) and appends them to el.
511 * @param {Mixed} el The context element
512 * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
513 * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
514 * @return {HTMLElement/Ext.core.Element} The new node
516 append : function(el, o, returnElement){
517 return doInsert(el, o, returnElement, beforeend, '', true);
520 <span id='Ext-core-DomHelper-method-overwrite'> /**
521 </span> * Creates new DOM element(s) and overwrites the contents of el with them.
522 * @param {Mixed} el The context element
523 * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
524 * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
525 * @return {HTMLElement/Ext.core.Element} The new node
527 overwrite : function(el, o, returnElement){
529 el.innerHTML = createHtml(o);
530 return returnElement ? Ext.get(el.firstChild) : el.firstChild;
533 createHtml : createHtml,
535 <span id='Ext-core-DomHelper-method-createDom'> /**
536 </span> * Creates new DOM element(s) without inserting them to the document.
537 * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
538 * @return {HTMLElement} The new uninserted node
541 createDom: createDom,
543 <span id='Ext-core-DomHelper-property-useDom'> /** True to force the use of DOM instead of html fragments @type Boolean */
544 </span> useDom : false,
546 <span id='Ext-core-DomHelper-method-createTemplate'> /**
547 </span> * Creates a new Ext.Template from the DOM object spec.
548 * @param {Object} o The DOM object spec (and children)
549 * @return {Ext.Template} The new template
551 createTemplate : function(o){
552 var html = Ext.core.DomHelper.createHtml(o);
553 return Ext.create('Ext.Template', html);