2 Copyright (c) 2010, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
8 YUI.add('dom-base', function(Y) {
12 * The DOM utility provides a cross-browser abtraction layer
13 * normalizing DOM tasks, and adds extra helper functionality
14 * for other common tasks.
22 * Provides DOM helper methods.
26 var NODE_TYPE = 'nodeType',
27 OWNER_DOCUMENT = 'ownerDocument',
28 DOCUMENT_ELEMENT = 'documentElement',
29 DEFAULT_VIEW = 'defaultView',
30 PARENT_WINDOW = 'parentWindow',
32 PARENT_NODE = 'parentNode',
33 FIRST_CHILD = 'firstChild',
34 PREVIOUS_SIBLING = 'previousSibling',
35 NEXT_SIBLING = 'nextSibling',
36 CONTAINS = 'contains',
37 COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition',
41 documentElement = Y.config.doc.documentElement,
43 re_tag = /<([a-z]+)/i,
45 createFromDIV = function(html, tag) {
46 var div = Y.config.doc.createElement('div'),
50 if (!div.firstChild || div.firstChild.tagName !== tag.toUpperCase()) {
57 addFeature = Y.Features.add,
58 testFeature = Y.Features.test,
62 * Returns the HTMLElement with the given ID (Wrapper for document.getElementById).
64 * @param {String} id the id attribute
65 * @param {Object} doc optional The document to search. Defaults to current document
66 * @return {HTMLElement | null} The HTMLElement with the id, or null if none found.
68 byId: function(id, doc) {
69 // handle dupe IDs and IE name collision
70 return Y_DOM.allById(id, doc)[0] || null;
74 * Returns the text content of the HTMLElement.
76 * @param {HTMLElement} element The html element.
77 * @return {String} The text content of the element (includes text of any descending elements).
79 getText: (documentElement.textContent !== undefined) ?
83 ret = element.textContent;
86 } : function(element) {
89 ret = element.innerText || element.nodeValue; // might be a textNode
95 * Sets the text content of the HTMLElement.
97 * @param {HTMLElement} element The html element.
98 * @param {String} content The content to add.
100 setText: (documentElement.textContent !== undefined) ?
101 function(element, content) {
103 element.textContent = content;
105 } : function(element, content) {
106 if ('innerText' in element) {
107 element.innerText = content;
108 } else if ('nodeValue' in element) {
109 element.nodeValue = content;
115 * Finds the ancestor of the element.
117 * @param {HTMLElement} element The html element.
118 * @param {Function} fn optional An optional boolean test to apply.
119 * The optional function is passed the current DOM node being tested as its only argument.
120 * If no function is given, the parentNode is returned.
121 * @param {Boolean} testSelf optional Whether or not to include the element in the scan
122 * @return {HTMLElement | null} The matching DOM node or null if none found.
124 ancestor: function(element, fn, testSelf) {
127 ret = (!fn || fn(element)) ? element : null;
130 return ret || Y_DOM.elementByAxis(element, PARENT_NODE, fn, null);
134 * Finds the ancestors of the element.
136 * @param {HTMLElement} element The html element.
137 * @param {Function} fn optional An optional boolean test to apply.
138 * The optional function is passed the current DOM node being tested as its only argument.
139 * If no function is given, all ancestors are returned.
140 * @param {Boolean} testSelf optional Whether or not to include the element in the scan
141 * @return {Array} An array containing all matching DOM nodes.
143 ancestors: function(element, fn, testSelf) {
144 var ancestor = Y_DOM.ancestor.apply(Y_DOM, arguments),
145 ret = (ancestor) ? [ancestor] : [];
147 while ((ancestor = Y_DOM.ancestor(ancestor, fn))) {
149 ret.unshift(ancestor);
157 * Searches the element by the given axis for the first matching element.
158 * @method elementByAxis
159 * @param {HTMLElement} element The html element.
160 * @param {String} axis The axis to search (parentNode, nextSibling, previousSibling).
161 * @param {Function} fn optional An optional boolean test to apply.
162 * @param {Boolean} all optional Whether all node types should be returned, or just element nodes.
163 * The optional function is passed the current HTMLElement being tested as its only argument.
164 * If no function is given, the first element is returned.
165 * @return {HTMLElement | null} The matching element or null if none found.
167 elementByAxis: function(element, axis, fn, all) {
168 while (element && (element = element[axis])) { // NOTE: assignment
169 if ( (all || element[TAG_NAME]) && (!fn || fn(element)) ) {
177 * Determines whether or not one HTMLElement is or contains another HTMLElement.
179 * @param {HTMLElement} element The containing html element.
180 * @param {HTMLElement} needle The html element that may be contained.
181 * @return {Boolean} Whether or not the element is or contains the needle.
183 contains: function(element, needle) {
186 if ( !needle || !element || !needle[NODE_TYPE] || !element[NODE_TYPE]) {
188 } else if (element[CONTAINS]) {
189 if (Y.UA.opera || needle[NODE_TYPE] === 1) { // IE & SAF contains fail if needle not an ELEMENT_NODE
190 ret = element[CONTAINS](needle);
192 ret = Y_DOM._bruteContains(element, needle);
194 } else if (element[COMPARE_DOCUMENT_POSITION]) { // gecko
195 if (element === needle || !!(element[COMPARE_DOCUMENT_POSITION](needle) & 16)) {
204 * Determines whether or not the HTMLElement is part of the document.
206 * @param {HTMLElement} element The containing html element.
207 * @param {HTMLElement} doc optional The document to check.
208 * @return {Boolean} Whether or not the element is attached to the document.
210 inDoc: function(element, doc) {
214 if (element && element.nodeType) {
215 (doc) || (doc = element[OWNER_DOCUMENT]);
217 rootNode = doc[DOCUMENT_ELEMENT];
219 // contains only works with HTML_ELEMENT
220 if (rootNode && rootNode.contains && element.tagName) {
221 ret = rootNode.contains(element);
223 ret = Y_DOM.contains(rootNode, element);
231 allById: function(id, root) {
232 root = root || Y.config.doc;
238 if (root.querySelectorAll) {
239 ret = root.querySelectorAll('[id="' + id + '"]');
240 } else if (root.all) {
241 nodes = root.all(id);
244 // root.all may return HTMLElement or HTMLCollection.
245 // some elements are also HTMLCollection (FORM, SELECT).
246 if (nodes.nodeName) {
247 if (nodes.id === id) { // avoid false positive on name
249 nodes = EMPTY_ARRAY; // done, no need to filter
250 } else { // prep for filtering
256 // filter out matches on node.name
257 // and element.id as reference to element with id === 'id'
258 for (i = 0; node = nodes[i++];) {
259 if (node.id === id ||
260 (node.attributes && node.attributes.id &&
261 node.attributes.id.value === id)) {
268 ret = [Y_DOM._getDoc(root).getElementById(id)];
275 * Creates a new dom node using the provided markup string.
277 * @param {String} html The markup used to create the element
278 * @param {HTMLDocument} doc An optional document context
279 * @return {HTMLElement|DocumentFragment} returns a single HTMLElement
280 * when creating one node, and a documentFragment when creating
283 create: function(html, doc) {
284 if (typeof html === 'string') {
285 html = Y.Lang.trim(html); // match IE which trims whitespace from innerHTML
289 doc = doc || Y.config.doc;
290 var m = re_tag.exec(html),
291 create = Y_DOM._create,
292 custom = Y_DOM.creators,
297 if (html != undefined) { // not undefined or null
299 creator = custom[m[1].toLowerCase()];
300 if (typeof creator === 'function') {
307 nodes = create(html, doc, tag).childNodes;
309 if (nodes.length === 1) { // return single node, breaking parentNode ref from "fragment"
310 ret = nodes[0].parentNode.removeChild(nodes[0]);
311 } else if (nodes[0] && nodes[0].className === 'yui3-big-dummy') { // using dummy node to preserve some attributes (e.g. OPTION not selected)
312 if (nodes.length === 2) {
313 ret = nodes[0].nextSibling;
315 nodes[0].parentNode.removeChild(nodes[0]);
316 ret = Y_DOM._nl2frag(nodes, doc);
318 } else { // return multiple nodes as a fragment
319 ret = Y_DOM._nl2frag(nodes, doc);
326 _nl2frag: function(nodes, doc) {
330 if (nodes && (nodes.push || nodes.item) && nodes[0]) {
331 doc = doc || nodes[0].ownerDocument;
332 ret = doc.createDocumentFragment();
334 if (nodes.item) { // convert live list to static array
335 nodes = Y.Array(nodes, 0, true);
338 for (i = 0, len = nodes.length; i < len; i++) {
339 ret.appendChild(nodes[i]);
341 } // else inline with log for minification
346 CUSTOM_ATTRIBUTES: (!documentElement.hasAttribute) ? { // IE < 8
355 * Provides a normalized attribute interface.
356 * @method setAttibute
357 * @param {HTMLElement} el The target element for the attribute.
358 * @param {String} attr The attribute to set.
359 * @param {String} val The value of the attribute.
361 setAttribute: function(el, attr, val, ieAttr) {
362 if (el && attr && el.setAttribute) {
363 attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr;
364 el.setAttribute(attr, val, ieAttr);
370 * Provides a normalized attribute interface.
371 * @method getAttibute
372 * @param {HTMLElement} el The target element for the attribute.
373 * @param {String} attr The attribute to get.
374 * @return {String} The current value of the attribute.
376 getAttribute: function(el, attr, ieAttr) {
377 ieAttr = (ieAttr !== undefined) ? ieAttr : 2;
379 if (el && attr && el.getAttribute) {
380 attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr;
381 ret = el.getAttribute(attr, ieAttr);
384 ret = ''; // per DOM spec
390 isWindow: function(obj) {
391 return !!(obj && obj.alert && obj.document);
396 _create: function(html, doc, tag) {
399 var frag = Y_DOM._fragClones[tag];
401 frag = frag.cloneNode(false);
403 frag = Y_DOM._fragClones[tag] = doc.createElement(tag);
405 frag.innerHTML = html;
409 _removeChildNodes: function(node) {
410 while (node.firstChild) {
411 node.removeChild(node.firstChild);
416 * Inserts content in a node at the given location
418 * @param {HTMLElement} node The node to insert into
419 * @param {HTMLElement | Array | HTMLCollection} content The content to be inserted
420 * @param {HTMLElement} where Where to insert the content
421 * If no "where" is given, content is appended to the node
422 * Possible values for "where"
424 * <dt>HTMLElement</dt>
425 * <dd>The element to insert before</dd>
427 * <dd>Replaces the existing HTML</dd>
429 * <dd>Inserts before the existing HTML</dd>
431 * <dd>Inserts content before the node</dd>
433 * <dd>Inserts content after the node</dd>
436 addHTML: function(node, content, where) {
437 var nodeParent = node.parentNode,
444 if (content != undefined) { // not null or undefined (maybe 0)
445 if (content.nodeType) { // DOM node, just add it
447 } else if (typeof content == 'string' || typeof content == 'number') {
448 ret = newNode = Y_DOM.create(content);
449 } else if (content[0] && content[0].nodeType) { // array or collection
450 newNode = Y.config.doc.createDocumentFragment();
451 while ((item = content[i++])) {
452 newNode.appendChild(item); // append to fragment for insertion
458 if (where.nodeType) { // insert regardless of relationship to node
459 where.parentNode.insertBefore(newNode, where);
463 while (node.firstChild) {
464 node.removeChild(node.firstChild);
466 if (newNode) { // allow empty content to clear node
467 node.appendChild(newNode);
471 nodeParent.insertBefore(newNode, node);
474 if (node.nextSibling) { // IE errors if refNode is null
475 nodeParent.insertBefore(newNode, node.nextSibling);
477 nodeParent.appendChild(newNode);
481 node.appendChild(newNode);
484 } else if (newNode) {
485 node.appendChild(newNode);
495 getValue: function(node) {
496 var ret = '', // TODO: return null?
499 if (node && node[TAG_NAME]) {
500 getter = Y_DOM.VALUE_GETTERS[node[TAG_NAME].toLowerCase()];
509 // workaround for IE8 JSON stringify bug
510 // which converts empty string values to null
511 if (ret === EMPTY_STRING) {
512 ret = EMPTY_STRING; // for real
515 return (typeof ret === 'string') ? ret : '';
518 setValue: function(node, val) {
521 if (node && node[TAG_NAME]) {
522 setter = Y_DOM.VALUE_SETTERS[node[TAG_NAME].toLowerCase()];
532 siblings: function(node, fn) {
536 while ((sibling = sibling[PREVIOUS_SIBLING])) {
537 if (sibling[TAG_NAME] && (!fn || fn(sibling))) {
538 nodes.unshift(sibling);
543 while ((sibling = sibling[NEXT_SIBLING])) {
544 if (sibling[TAG_NAME] && (!fn || fn(sibling))) {
553 * Brute force version of contains.
554 * Used for browsers without contains support for non-HTMLElement Nodes (textNodes, etc).
555 * @method _bruteContains
557 * @param {HTMLElement} element The containing html element.
558 * @param {HTMLElement} needle The html element that may be contained.
559 * @return {Boolean} Whether or not the element is or contains the needle.
561 _bruteContains: function(element, needle) {
563 if (element === needle) {
566 needle = needle.parentNode;
571 // TODO: move to Lang?
573 * Memoizes dynamic regular expressions to boost runtime performance.
576 * @param {String} str The string to convert to a regular expression.
577 * @param {String} flags optional An optinal string of flags.
578 * @return {RegExp} An instance of RegExp
580 _getRegExp: function(str, flags) {
582 Y_DOM._regexCache = Y_DOM._regexCache || {};
583 if (!Y_DOM._regexCache[str + flags]) {
584 Y_DOM._regexCache[str + flags] = new RegExp(str, flags);
586 return Y_DOM._regexCache[str + flags];
589 // TODO: make getDoc/Win true privates?
591 * returns the appropriate document.
594 * @param {HTMLElement} element optional Target element.
595 * @return {Object} The document for the given element or the default document.
597 _getDoc: function(element) {
598 var doc = Y.config.doc;
600 doc = (element[NODE_TYPE] === 9) ? element : // element === document
601 element[OWNER_DOCUMENT] || // element === DOM node
602 element.document || // element === window
603 Y.config.doc; // default
610 * returns the appropriate window.
613 * @param {HTMLElement} element optional Target element.
614 * @return {Object} The window for the given element or the default window.
616 _getWin: function(element) {
617 var doc = Y_DOM._getDoc(element);
618 return doc[DEFAULT_VIEW] || doc[PARENT_WINDOW] || Y.config.win;
621 _batch: function(nodes, fn, arg1, arg2, arg3, etc) {
622 fn = (typeof fn === 'string') ? Y_DOM[fn] : fn;
624 args = Array.prototype.slice.call(arguments, 2),
630 while ((node = nodes[i++])) {
631 result = result = fn.call(Y_DOM, node, arg1, arg2, arg3, etc);
632 if (typeof result !== 'undefined') {
639 return (typeof ret !== 'undefined') ? ret : nodes;
642 wrap: function(node, html) {
643 var parent = Y.DOM.create(html),
644 nodes = parent.getElementsByTagName('*');
647 parent = nodes[nodes.length - 1];
650 if (node.parentNode) {
651 node.parentNode.replaceChild(parent, node);
653 parent.appendChild(node);
656 unwrap: function(node) {
657 var parent = node.parentNode,
658 lastChild = parent.lastChild,
659 node = parent.firstChild,
664 grandparent = parent.parentNode;
666 while (node !== lastChild) {
667 next = node.nextSibling;
668 grandparent.insertBefore(node, parent);
671 grandparent.replaceChild(lastChild, parent);
673 parent.removeChild(node);
678 generateID: function(el) {
692 addFeature('innerhtml', 'table', {
694 var node = Y.config.doc.createElement('table');
696 node.innerHTML = '<tbody></tbody>';
700 return (node.firstChild && node.firstChild.nodeName === 'TBODY');
704 addFeature('innerhtml-div', 'tr', {
706 return createFromDIV('<tr></tr>', 'tr');
710 addFeature('innerhtml-div', 'script', {
712 return createFromDIV('<script></script>', 'script');
716 addFeature('value-set', 'select', {
718 var node = Y.config.doc.createElement('select');
719 node.innerHTML = '<option>1</option><option>2</option>';
721 return (node.value && node.value === '2');
726 var creators = Y_DOM.creators,
727 create = Y_DOM.create,
728 re_tbody = /(?:\/(?:thead|tfoot|tbody|caption|col|colgroup)>)+\s*<tbody/,
730 TABLE_OPEN = '<table>',
731 TABLE_CLOSE = '</table>';
733 if (!testFeature('innerhtml', 'table')) {
734 // TODO: thead/tfoot with nested tbody
735 // IE adds TBODY when creating TABLE elements (which may share this impl)
736 creators.tbody = function(html, doc) {
737 var frag = create(TABLE_OPEN + html + TABLE_CLOSE, doc),
738 tb = frag.children.tags('tbody')[0];
740 if (frag.children.length > 1 && tb && !re_tbody.test(html)) {
741 tb[PARENT_NODE].removeChild(tb); // strip extraneous tbody
747 if (!testFeature('innerhtml-div', 'script')) {
748 creators.script = function(html, doc) {
749 var frag = doc.createElement('div');
751 frag.innerHTML = '-' + html;
752 frag.removeChild(frag[FIRST_CHILD]);
756 Y_DOM.creators.link = Y_DOM.creators.style = Y_DOM.creators.script;
760 if (!testFeature('value-set', 'select')) {
761 Y_DOM.VALUE_SETTERS.select = function(node, val) {
762 for (var i = 0, options = node.getElementsByTagName('option'), option;
763 option = options[i++];) {
764 if (Y_DOM.getValue(option) === val) {
765 option.selected = true;
766 //Y_DOM.setAttribute(option, 'selected', 'selected');
773 Y.mix(Y_DOM.VALUE_GETTERS, {
774 button: function(node) {
775 return (node.attributes && node.attributes.value) ? node.attributes.value.value : '';
779 Y.mix(Y_DOM.VALUE_SETTERS, {
780 // IE: node.value changes the button text, which should be handled via innerHTML
781 button: function(node, val) {
782 var attr = node.attributes.value;
784 attr = node[OWNER_DOCUMENT].createAttribute('value');
785 node.setAttributeNode(attr);
793 if (!testFeature('innerhtml-div', 'tr')) {
795 option: function(html, doc) {
796 return create('<select><option class="yui3-big-dummy" selected></option>' + html + '</select>', doc);
799 tr: function(html, doc) {
800 return create('<tbody>' + html + '</tbody>', doc);
803 td: function(html, doc) {
804 return create('<tr>' + html + '</tr>', doc);
807 col: function(html, doc) {
808 return create('<colgroup>' + html + '</colgroup>', doc);
817 thead: creators.tbody,
818 tfoot: creators.tbody,
819 caption: creators.tbody,
820 colgroup: creators.tbody,
821 optgroup: creators.option
825 Y.mix(Y_DOM.VALUE_GETTERS, {
826 option: function(node) {
827 var attrs = node.attributes;
828 return (attrs.value && attrs.value.specified) ? node.value : node.text;
831 select: function(node) {
832 var val = node.value,
833 options = node.options;
835 if (options && options.length) {
836 // TODO: implement multipe select
839 val = Y_DOM.getValue(options[node.selectedIndex]);
850 var addClass, hasClass, removeClass;
854 * Determines whether a DOM element has the given className.
857 * @param {HTMLElement} element The DOM element.
858 * @param {String} className the class name to search for
859 * @return {Boolean} Whether or not the element has the given class.
861 hasClass: function(node, className) {
862 var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');
863 return re.test(node.className);
867 * Adds a class name to a given DOM element.
870 * @param {HTMLElement} element The DOM element.
871 * @param {String} className the class name to add to the class attribute
873 addClass: function(node, className) {
874 if (!Y.DOM.hasClass(node, className)) { // skip if already present
875 node.className = Y.Lang.trim([node.className, className].join(' '));
880 * Removes a class name from a given element.
881 * @method removeClass
883 * @param {HTMLElement} element The DOM element.
884 * @param {String} className the class name to remove from the class attribute
886 removeClass: function(node, className) {
887 if (className && hasClass(node, className)) {
888 node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' +
889 className + '(?:\\s+|$)'), ' '));
891 if ( hasClass(node, className) ) { // in case of multiple adjacent
892 removeClass(node, className);
898 * Replace a class with another class for a given element.
899 * If no oldClassName is present, the newClassName is simply added.
900 * @method replaceClass
902 * @param {HTMLElement} element The DOM element
903 * @param {String} oldClassName the class name to be replaced
904 * @param {String} newClassName the class name that will be replacing the old class name
906 replaceClass: function(node, oldC, newC) {
907 removeClass(node, oldC); // remove first in case oldC === newC
908 addClass(node, newC);
912 * If the className exists on the node it is removed, if it doesn't exist it is added.
913 * @method toggleClass
915 * @param {HTMLElement} element The DOM element
916 * @param {String} className the class name to be toggled
917 * @param {Boolean} addClass optional boolean to indicate whether class
918 * should be added or removed regardless of current state
920 toggleClass: function(node, className, force) {
921 var add = (force !== undefined) ? force :
922 !(hasClass(node, className));
925 addClass(node, className);
927 removeClass(node, className);
932 hasClass = Y.DOM.hasClass;
933 removeClass = Y.DOM.removeClass;
934 addClass = Y.DOM.addClass;
938 * Sets the width of the element to the given size, regardless
939 * of box model, border, padding, etc.
941 * @param {HTMLElement} element The DOM element.
942 * @param {String|Int} size The pixel height to size to
945 setWidth: function(node, size) {
946 Y.DOM._setSize(node, 'width', size);
950 * Sets the height of the element to the given size, regardless
951 * of box model, border, padding, etc.
953 * @param {HTMLElement} element The DOM element.
954 * @param {String|Int} size The pixel height to size to
957 setHeight: function(node, size) {
958 Y.DOM._setSize(node, 'height', size);
961 _setSize: function(node, prop, val) {
962 val = (val > 0) ? val : 0;
965 node.style[prop] = val + 'px';
966 size = (prop === 'height') ? node.offsetHeight : node.offsetWidth;
969 val = val - (size - val);
975 node.style[prop] = val + 'px';
981 }, '3.3.0' ,{requires:['oop']});