2
Copyright (c) 2008, Yahoo! Inc. All rights reserved.
3
Code licensed under the BSD License:
4
http://developer.yahoo.net/yui/license.txt
7
YUI.add('node-base', function(Y) {
10
* The Node Utility provides a DOM-like interface for interacting with DOM nodes.
12
* @submodule node-base
16
* The Node class provides a wrapper for manipulating DOM Nodes.
17
* Node properties can be accessed via the set/get methods.
18
* Use Y.get() to retrieve Node instances.
20
* <strong>NOTE:</strong> All node properties are accessed using the
21
* <code>set</code> and <code>get</code> methods.
31
//CDATA_SECTION_NODE = 4,
32
//ENTITY_REFERENCE_NODE = 5,
34
//PROCESSING_INSTRUCTION_NODE = 7,
36
DOCUMENT_NODE = 9; //,
37
//DOCUMENT_TYPE_NODE = 10,
38
//DOCUMENT_FRAGMENT_NODE = 11,
41
var OWNER_DOCUMENT = 'ownerDocument',
43
NODE_NAME = 'nodeName',
44
NODE_TYPE = 'nodeType';
46
var RE_VALID_PROP_TYPES = /(?:string|boolean|number)/;
48
var Selector = Y.Selector;
56
var wrapDOM = function(node) {
58
yuid = (node) ? node._yuid : null,
59
instance = _instances[yuid],
60
existingNode = _nodes[yuid];
63
if (NODE_TYPE in node) {
64
if (instance && existingNode && node === existingNode) {
65
ret = instance; // reuse existing Nodes if nodes match
69
} else if ('item' in node || 'push' in node) {
70
ret = new Y.NodeList(node);
76
var wrapFn = function(fn) {
79
ret = (typeof fn === 'string') ?
81
return Y.Selector.test(n, fn);
84
return fn(_instances[n._yuid]);
91
var getDoc = function(node) {
92
node = _nodes[node._yuid];
93
return (node[NODE_TYPE] === 9) ? node : node[OWNER_DOCUMENT];
96
// returns HTMLElement
97
var getDOMNode = function(node) {
98
if (node && !node.nodeType && node._yuid) {
99
node = _nodes[node._yuid];
107
* Wraps the input and outputs of a node instance
109
var nodeInOut = function(method, a, b, c, d, e) {
110
if (a) { // first 2 may be Node instances or nodes (TODO: or strings?)
116
return wrapDOM(_nodes[this._yuid][method](a, b, c, d, e));
120
* Wraps the return value in a node instance
122
var nodeOut = function(method, a, b, c, d, e) {
123
return wrapDOM(_nodes[this._yuid][method](a, b, c, d, e));
127
* Returns directy from node method call
129
var rawOut = function(method, a, b, c, d, e) {
130
return _nodes[this._yuid][method](a, b, c, d, e);
133
var noOut = function(method, a, b, c, d, e) {
134
_nodes[this._yuid][method](a, b, c, d, e);
140
* Returns a Node instance.
141
* @property parentNode
144
'parentNode': BASE_NODE,
147
* Returns a NodeList instance.
148
* @property childNodes
151
'childNodes': BASE_NODE,
154
* Returns a NodeList instance.
158
'children': function(node) {
159
node = _nodes[node._yuid];
160
var children = node.children;
162
if (children === undefined) {
163
var childNodes = node.childNodes;
166
for (var i = 0, len = childNodes.length; i < len; ++i) {
167
if (childNodes[i][TAG_NAME]) {
168
children[children.length] = childNodes[i];
176
* Returns a Node instance.
177
* @property firstChild
180
'firstChild': BASE_NODE,
183
* Returns a Node instance.
184
* @property lastChild
187
'lastChild': BASE_NODE,
190
* Returns a Node instance.
191
* @property previousSibling
194
'previousSibling': BASE_NODE,
197
* Returns a Node instance.
198
* @property previousSibling
201
'nextSibling': BASE_NODE,
204
* Returns a Node instance.
205
* @property ownerDocument
208
'ownerDocument': BASE_NODE,
211
* Returns a Node instance.
212
* @property offsetParent
215
'offsetParent': ELEMENT_NODE,
218
* Returns a Node instance.
219
* @property documentElement
222
'documentElement': DOCUMENT_NODE,
225
* Returns a Node instance.
229
'body': DOCUMENT_NODE,
233
* Returns a NodeList instance.
237
'elements': ELEMENT_NODE,
241
* Returns a NodeList instance.
245
'rows': ELEMENT_NODE,
248
* Returns a NodeList instance.
252
'cells': ELEMENT_NODE,
255
* Returns a Node instance.
259
'tHead': ELEMENT_NODE,
262
* Returns a Node instance.
266
'tFoot': ELEMENT_NODE,
269
* Returns a NodeList instance.
273
'tBodies': ELEMENT_NODE
277
* Passes through to DOM method.
278
* @method replaceChild
279
* @param {HTMLElement | Node} node Node to be inserted
280
* @param {HTMLElement | Node} refNode Node to be replaced
281
* @return {Node} The replaced node
283
replaceChild: nodeInOut,
286
* Passes through to DOM method.
287
* @method appendChild
288
* @param {HTMLElement | Node} node Node to be appended
289
* @return {Node} The appended node
291
appendChild: nodeInOut,
294
* Passes through to DOM method.
295
* @method insertBefore
296
* @param {HTMLElement | Node} newNode Node to be appended
297
* @param {HTMLElement | Node} refNode Node to be inserted before
298
* @return {Node} The inserted node
300
insertBefore: nodeInOut,
303
* Passes through to DOM method.
304
* @method removeChild
305
* @param {HTMLElement | Node} node Node to be removed
306
* @return {Node} The removed node
308
removeChild: nodeInOut,
311
* Passes through to DOM method.
312
* @method hasChildNodes
313
* @return {Boolean} Whether or not the node has any childNodes
315
hasChildNodes: rawOut,
318
* Passes through to DOM method.
320
* @param {HTMLElement | Node} node Node to be cloned
321
* @return {Node} The clone
326
* Passes through to DOM method.
327
* @method getAttribute
328
* @param {String} attribute The attribute to retrieve
329
* @return {String} The current value of the attribute
331
getAttribute: rawOut,
334
* Passes through to DOM method.
335
* @method setAttribute
336
* @param {String} attribute The attribute to set
337
* @param {String} The value to apply to the attribute
343
* Passes through to DOM method.
344
* @method hasAttribute
345
* @param {String} attribute The attribute to test for
346
* @return {Boolean} Whether or not the attribute is present
348
hasAttribute: rawOut,
351
* Passes through to DOM method.
352
* @method scrollIntoView
355
scrollIntoView: noOut,
358
* Passes through to DOM method.
359
* @method getElementsByTagName
360
* @param {String} tagName The tagName to collect
361
* @return {NodeList} A NodeList representing the HTMLCollection
363
getElementsByTagName: nodeOut,
366
* Passes through to DOM method.
373
* Passes through to DOM method.
380
* Passes through to DOM method.
381
* Only valid on FORM elements
388
* Passes through to DOM method.
389
* Only valid on FORM elements
396
var addNodeListMethod = function(name) {
397
NodeList.prototype[name] = function() {
399
nodes = _nodelists[this._yuid],
402
for (var i = 0, len = nodes.length; i < len; ++i) {
403
_nodes[_tmpNode._yuid] = nodes[i];
404
ret = _tmpNode[name].apply(_tmpNode, arguments);
405
if (ret !== _tmpNode) {
410
return a.length ? a : this;
414
var METHODS_INVOKE = {
415
'getBoundingClientRect': true
418
var Node = function(node) {
419
if (!node || !node[NODE_TYPE]) {
424
try { // IE errors on non-element expandos (cant be reused)
429
_instances[yuid] = this;
436
* Normalizes nodeInnerText and textContent.
440
'text': function(node) {
441
return Y.DOM.getText(_nodes[node._yuid]);
445
* Returns a nodeList of option elements
449
'options': function(node) {
450
return (node) ? node.getElementsByTagName('option') : [];
454
Node.setters = function(prop, fn) {
455
if (typeof prop == 'string') {
457
} else { // assume object
458
Y.each(prop, function(fn, prop) {
459
Node.setters(prop, fn);
464
Node.getters = function(prop, fn) {
465
if (typeof prop == 'string') {
467
} else { // assume object
468
Y.each(prop, function(fn, prop) {
469
Node.getters(prop, fn);
474
Node.methods = function(name, fn) {
475
if (typeof name == 'string') {
476
Node.prototype[name] = function() {
477
var args = slice.call(arguments);
479
var ret = fn.apply(null, args);
480
if (ret === undefined) {
486
addNodeListMethod(name);
489
} else { // assume object
490
Y.each(name, function(fn, name) {
491
Node.methods(name, fn);
496
Node.getDOMNode = function(node) {
501
} else if (typeof node === 'string') {
502
ret = Selector.query(node, null, true);
504
ret = _nodes[node._yuid];
509
Node.wrapDOMMethod = function(name) {
511
var args = slice.call(arguments);
512
args.unshift(Y.Node.getDOMNode(args.shift()));
513
return Y.DOM[name].apply(Y.DOM, args);
518
Node.addDOMMethods = function(methods) {
520
Y.each(methods, function(v, n) {
521
add[v] = Y.Node.wrapDOMMethod(v);
529
* Set the value of the property/attribute on the HTMLElement bound to this Node.
530
* Only strings/numbers/booleans are passed through unless a SETTER exists.
532
* @param {String} prop Property to set
533
* @param {any} val Value to apply to the given property
536
set: function(prop, val) {
537
var node = _nodes[this._yuid];
538
if (prop in SETTERS) { // use custom setter
539
SETTERS[prop](this, prop, val); // passing Node instance
540
} else if (RE_VALID_PROP_TYPES.test(typeof node[prop])) { // safe to write
547
* Get the value of the property/attribute on the HTMLElement bound to this Node.
548
* Only strings/numbers/booleans are passed through unless a GETTER exists.
550
* @param {String} prop Property to get
551
* @return {any} Current value of the property
553
get: function(prop) {
555
var node = _nodes[this._yuid];
556
if (prop in GETTERS) { // use custom getter
557
val = GETTERS[prop](this, prop);
558
} else if (prop in PROPS_WRAP) { // wrap DOM object (HTMLElement, HTMLCollection, Document)
559
if (typeof PROPS_WRAP[prop] === 'function') {
560
val = PROPS_WRAP[prop](this);
565
if (_restrict && _restrict[this._yuid] && !Y.DOM.contains(node, val)) {
566
val = null; // not allowed to go outside of root node
570
} else if (RE_VALID_PROP_TYPES.test(typeof node[prop])) { // safe to read
576
invoke: function(method, a, b, c, d, e) {
577
if (a) { // first 2 may be Node instances or strings
578
a = (a[NODE_TYPE]) ? a : getDOMNode(a);
580
b = (b[NODE_TYPE]) ? b : getDOMNode(b);
583
var node = _nodes[this._yuid];
584
if (node && METHODS_INVOKE[method] && node[method]) {
585
return node[method](a, b, c, d, e);
590
hasMethod: function(method) {
591
return !!(METHODS_INVOKE[method] && _nodes[this._yuid][method]);
594
//normalize: function() {},
595
//isSupported: function(feature, version) {},
596
toString: function() {
597
var node = _nodes[this._yuid] || {};
598
return node.id || node[NODE_NAME] || 'undefined node';
602
* Retrieves a single node based on the given CSS selector.
605
* @param {string} selector The CSS selector to test against.
606
* @return {Node} A Node instance for the matching HTMLElement.
608
query: function(selector) {
609
return wrapDOM(Selector.query(selector, _nodes[this._yuid], true));
613
* Retrieves a nodeList based on the given CSS selector.
616
* @param {string} selector The CSS selector to test against.
617
* @return {NodeList} A NodeList instance for the matching HTMLCollection/Array.
619
queryAll: function(selector) {
620
return wrapDOM(Selector.query(selector, _nodes[this._yuid]));
624
* Test if the supplied node matches the supplied selector.
627
* @param {string} selector The CSS selector to test against.
628
* @return {boolean} Whether or not the node matches the selector.
630
test: function(selector) {
631
return Selector.test(_nodes[this._yuid], selector);
635
* Compares nodes to determine if they match.
636
* Node instances can be compared to each other and/or HTMLElements.
638
* @param {HTMLElement | Node} refNode The reference node to compare to the node.
639
* @return {Boolean} True if the nodes match, false if they do not.
641
compareTo: function(refNode) {
642
refNode = refNode[NODE_TYPE] ? refNode : _nodes[refNode._yuid];
643
return _nodes[this._yuid] === refNode;
647
* Returns the nearest ancestor that passes the test applied by supplied boolean method.
649
* @param {String | Function} fn A selector or boolean method for testing elements.
650
* If a function is used, it receives the current node being tested as the only argument.
651
* @return {Node} The matching Node instance or null if not found
653
ancestor: function(fn) {
654
return wrapDOM(Y.DOM.elementByAxis(_nodes[this._yuid], 'parentNode', wrapFn(fn)));
658
* Returns the previous matching sibling.
659
* Returns the nearest element node sibling if no method provided.
661
* @param {String | Function} fn A selector or boolean method for testing elements.
662
* If a function is used, it receives the current node being tested as the only argument.
663
* @param {Boolean} all optional Whether all node types should be returned, or just element nodes.
664
* @return {Node} Node instance or null if not found
666
previous: function(fn, all) {
667
return wrapDOM(Y.DOM.elementByAxis(_nodes[this._yuid], 'previousSibling', wrapFn(fn)), all);
671
* Returns the next matching sibling.
672
* Returns the nearest element node sibling if no method provided.
674
* @param {String | Function} fn A selector or boolean method for testing elements.
675
* If a function is used, it receives the current node being tested as the only argument.
676
* @param {Boolean} all optional Whether all node types should be returned, or just element nodes.
677
* @return {Node} Node instance or null if not found
679
next: function(fn, all) {
680
return wrapDOM(Y.DOM.elementByAxis(_nodes[this._yuid], 'nextSibling', wrapFn(fn)), all);
684
* Attaches a DOM event handler.
686
* @param {String} type The type of DOM Event to listen for
687
* @param {Function} fn The handler to call when the event fires
688
* @param {Object} arg An argument object to pass to the handler
691
attach: function(type, fn, arg) {
692
var args = slice.call(arguments, 0);
693
args.unshift(_nodes[this._yuid]);
694
return Y.Event.addListener.apply(Y.Event, args);
700
* @param {String} type The type of DOM Event to listen for
701
* @param {Function} fn The handler to call when the event fires
702
* @param {Object} arg An argument object to pass to the handler
706
on: function(type, fn, arg) {
707
return this.attach.apply(this, arguments);
710
addEventListener: function(type, fn, arg) {
711
return Y.Event.nativeAdd(_nodes[this._yuid], type, fn, arg);
715
* Detaches a DOM event handler.
717
* @param {String} type The type of DOM Event
718
* @param {Function} fn The handler to call when the event fires
720
detach: function(type, fn) {
721
var args = slice.call(arguments, 0);
722
args.unshift(_nodes[this._yuid]);
723
return Y.Event.removeListener.apply(Y.Event, args);
726
removeEventListener: function(type, fn) {
727
return Y.Event.nativeRemove(_nodes[this._yuid], type, fn);
731
* Creates a Node instance from HTML string
733
* @param {String|Array} html The string of html to create
734
* @return {Node} A new Node instance
736
create: function(html) {
737
return Y.Node.create(html);
741
* Determines whether the ndoe is an ancestor of another HTML element in the DOM hierarchy.
743
* @param {Node | HTMLElement} needle The possible node or descendent
744
* @return {Boolean} Whether or not this node is the needle its ancestor
746
contains: function(needle) {
747
return Y.DOM.contains(_nodes[this._yuid], getDOMNode(needle));
751
* Applies the supplied plugin to the node.
753
* @param {Function} The plugin Class to apply
754
* @param {Object} config An optional config to pass to the constructor
757
plug: function(PluginClass, config) {
758
config = config || {};
760
if (PluginClass && PluginClass.NS) {
761
this[PluginClass.NS] = new PluginClass(config);
767
* Determines whether the node is appended to the document.
769
* @param {Node|HTMLElement} doc optional An optional document to check against.
770
* Defaults to current document.
771
* @return {Boolean} Whether or not this node is appended to the document.
773
inDoc: function(doc) {
774
var node = _nodes[this._yuid];
775
doc = (doc) ? getDoc(doc) : node.ownerDocument;
776
if (doc.documentElement) {
777
return Y.DOM.contains(doc.documentElement, node);
782
Y.each(METHODS, function(fn, method) {
783
Node.prototype[method] = function() {
784
return fn.apply(this, [method].concat(slice.call(arguments)));
789
* Creates a Node instance from an HTML string
791
* @param {String} html HTML string
793
Node.create = function(html) {
794
return wrapDOM(Y.DOM.create(html));
797
Node.getById = function(id, doc) {
798
doc = (doc && doc[NODE_TYPE]) ? doc : Y.config.doc;
799
return wrapDOM(doc.getElementById(id));
803
* Retrieves a Node instance for the given object/string.
804
* Note: Use 'document' string to retrieve document Node instance from string
807
* @param {document|HTMLElement|HTMLCollection|Array|String} node The object to wrap.
808
* @param {document|Node} doc optional The document containing the node. Defaults to current document.
809
* @param {boolean} isRoot optional Whether or not this node should be treated as a root node. Root nodes
810
* aren't allowed to traverse outside their DOM tree.
811
* @return {Node} A wrapper instance for the supplied object.
813
Node.get = function(node, doc, isRoot) {
814
if (node instanceof Node) {
820
} else if (doc._yuid && _nodes[doc._yuid]) {
821
doc = _nodes[doc._yuid];
824
if (node && typeof node === 'string') {
825
if (node === 'document') {
828
node = Y.Selector.query(node, doc, true);
832
node = wrapDOM(node);
835
_restrict = _restrict || {};
836
_restrict[node._yuid] = node;
843
* Retrieves a NodeList instance for the given object/string.
846
* @param {HTMLCollection|Array|String} node The object to wrap.
847
* @param {document|Node} doc optional The document containing the node. Defaults to current document.
848
* @return {NodeList} A NodeList instance for the supplied nodes.
850
Node.all = function(nodes, doc) {
851
if (nodes instanceof NodeList) {
857
} else if (doc._yuid && _nodes[doc._yuid]) {
858
doc = _nodes[doc._yuid];
861
if (nodes && typeof nodes == 'string') {
862
nodes = Selector.query(nodes, doc);
865
return wrapDOM(nodes);
870
* A wrapper for manipulating multiple DOM elements
875
var NodeList = function(nodes) {
876
// TODO: input validation
877
_nodelists[Y.stamp(this)] = nodes;
880
// used to call Node methods against NodeList nodes
881
var _tmpNode = Node.create('<div></div>');
882
NodeList.prototype = {};
884
Y.each(Node.prototype, function(fn, name) {
885
if (typeof Node.prototype[name] == 'function') {
886
addNodeListMethod(name);
890
Y.mix(NodeList.prototype, {
892
* Retrieves the Node instance at the given index.
895
* @param {Number} index The index of the target Node.
896
* @return {Node} The Node instance at the given index.
898
item: function(index) {
899
var node = _nodelists[this._yuid][index];
900
return (node && node[TAG_NAME]) ? wrapDOM(node) : (node && node.get) ? node : null;
904
* Set the value of the property/attribute on all HTMLElements bound to this NodeList.
905
* Only strings/numbers/booleans are passed through unless a SETTER exists.
907
* @param {String} prop Property to set
908
* @param {any} val Value to apply to the given property
912
set: function(name, val) {
913
var nodes = _nodelists[this._yuid];
914
for (var i = 0, len = nodes.length; i < len; ++i) {
915
_nodes[_tmpNode._yuid] = nodes[i];
916
_tmpNode.set(name, val);
923
* Get the value of the property/attribute for each of the HTMLElements bound to this NodeList.
924
* Only strings/numbers/booleans are passed through unless a GETTER exists.
926
* @param {String} prop Property to get
927
* @return {Array} Array containing the current values mapped to the Node indexes
930
get: function(name) {
931
if (name == 'length') { // TODO: remove
932
return _nodelists[this._yuid].length;
934
var nodes = _nodelists[this._yuid];
936
for (var i = 0, len = nodes.length; i < len; ++i) {
937
_nodes[_tmpNode._yuid] = nodes[i];
938
ret[i] = _tmpNode.get(name);
945
* Filters the NodeList instance down to only nodes matching the given selector.
947
* @param {String} selector The selector to filter against
948
* @return {NodeList} NodeList containing the updated collection
951
filter: function(selector) {
952
return wrapDOM(Selector.filter(_nodelists[this._yuid], selector));
956
* Applies the given function to each Node in the NodeList.
958
* @param {Function} fn The function to apply
959
* @param {Object} context optional An optional context to apply the function with
960
* Default context is the NodeList instance
961
* @return {NodeList} NodeList containing the updated collection
964
each: function(fn, context) {
965
context = context || this;
966
var nodes = _nodelists[this._yuid];
967
for (var i = 0, len = nodes.length; i < len; ++i) {
968
fn.call(context, Y.Node.get(nodes[i]), i, this);
974
* Returns the current number of items in the NodeList.
976
* @return {Int} The number of items in the NodeList.
979
return _nodelists[this._yuid].length;
982
toString: function() {
983
var nodes = _nodelists[this._yuid] || [];
984
return 'NodeList (' + nodes.length + ' items)';
990
Y.NodeList = NodeList;
994
* Extended Node interface for managing classNames.
999
Y.Node.addDOMMethods([
1001
* Determines whether the node has the given className.
1003
* @param {String} className the class name to search for
1004
* @return {Boolean} Whether or not the node has the given class.
1009
* Adds a class name to the node.
1011
* @param {String} className the class name to add to the node's class attribute
1017
* Removes a class name from the node.
1018
* @method removeClass
1019
* @param {String} className the class name to remove from the node's class attribute
1025
* Replace a class with another class.
1026
* If no oldClassName is present, the newClassName is simply added.
1027
* @method replaceClass
1028
* @param {String} oldClassName the class name to be replaced
1029
* @param {String} newClassName the class name that will be replacing the old class name
1035
* If the className exists on the node it is removed, if it doesn't exist it is added.
1036
* @method toggleClass
1037
* @param {String} className the class name to be toggled
1044
}, '3.0.0pr1' ,{requires:['dom-base', 'selector']});