3
Copyright 2012 Yahoo! Inc. All rights reserved.
4
Licensed under the BSD License.
5
http://yuilibrary.com/license/
7
YUI.add('dom-base', function(Y) {
13
var documentElement = Y.config.doc.documentElement,
16
OWNER_DOCUMENT = 'ownerDocument',
18
addFeature = Y.Features.add,
19
testFeature = Y.Features.test;
23
* Returns the text content of the HTMLElement.
25
* @param {HTMLElement} element The html element.
26
* @return {String} The text content of the element (includes text of any descending elements).
28
getText: (documentElement.textContent !== undefined) ?
32
ret = element.textContent;
35
} : function(element) {
38
ret = element.innerText || element.nodeValue; // might be a textNode
44
* Sets the text content of the HTMLElement.
46
* @param {HTMLElement} element The html element.
47
* @param {String} content The content to add.
49
setText: (documentElement.textContent !== undefined) ?
50
function(element, content) {
52
element.textContent = content;
54
} : function(element, content) {
55
if ('innerText' in element) {
56
element.innerText = content;
57
} else if ('nodeValue' in element) {
58
element.nodeValue = content;
62
CUSTOM_ATTRIBUTES: (!documentElement.hasAttribute) ? { // IE < 8
71
* Provides a normalized attribute interface.
72
* @method setAttribute
73
* @param {HTMLElement} el The target element for the attribute.
74
* @param {String} attr The attribute to set.
75
* @param {String} val The value of the attribute.
77
setAttribute: function(el, attr, val, ieAttr) {
78
if (el && attr && el.setAttribute) {
79
attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr;
80
el.setAttribute(attr, val, ieAttr);
82
else { Y.log('bad input to setAttribute', 'warn', 'dom'); }
87
* Provides a normalized attribute interface.
88
* @method getAttribute
89
* @param {HTMLElement} el The target element for the attribute.
90
* @param {String} attr The attribute to get.
91
* @return {String} The current value of the attribute.
93
getAttribute: function(el, attr, ieAttr) {
94
ieAttr = (ieAttr !== undefined) ? ieAttr : 2;
96
if (el && attr && el.getAttribute) {
97
attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr;
98
ret = el.getAttribute(attr, ieAttr);
101
ret = ''; // per DOM spec
104
else { Y.log('bad input to getAttribute', 'warn', 'dom'); }
112
getValue: function(node) {
113
var ret = '', // TODO: return null?
116
if (node && node[TAG_NAME]) {
117
getter = Y_DOM.VALUE_GETTERS[node[TAG_NAME].toLowerCase()];
126
// workaround for IE8 JSON stringify bug
127
// which converts empty string values to null
128
if (ret === EMPTY_STRING) {
129
ret = EMPTY_STRING; // for real
132
return (typeof ret === 'string') ? ret : '';
135
setValue: function(node, val) {
138
if (node && node[TAG_NAME]) {
139
setter = Y_DOM.VALUE_SETTERS[node[TAG_NAME].toLowerCase()];
152
addFeature('value-set', 'select', {
154
var node = Y.config.doc.createElement('select');
155
node.innerHTML = '<option>1</option><option>2</option>';
157
return (node.value && node.value === '2');
161
if (!testFeature('value-set', 'select')) {
162
Y_DOM.VALUE_SETTERS.select = function(node, val) {
163
for (var i = 0, options = node.getElementsByTagName('option'), option;
164
option = options[i++];) {
165
if (Y_DOM.getValue(option) === val) {
166
option.selected = true;
167
//Y_DOM.setAttribute(option, 'selected', 'selected');
174
Y.mix(Y_DOM.VALUE_GETTERS, {
175
button: function(node) {
176
return (node.attributes && node.attributes.value) ? node.attributes.value.value : '';
180
Y.mix(Y_DOM.VALUE_SETTERS, {
181
// IE: node.value changes the button text, which should be handled via innerHTML
182
button: function(node, val) {
183
var attr = node.attributes.value;
185
attr = node[OWNER_DOCUMENT].createAttribute('value');
186
node.setAttributeNode(attr);
194
Y.mix(Y_DOM.VALUE_GETTERS, {
195
option: function(node) {
196
var attrs = node.attributes;
197
return (attrs.value && attrs.value.specified) ? node.value : node.text;
200
select: function(node) {
201
var val = node.value,
202
options = node.options;
204
if (options && options.length) {
205
// TODO: implement multipe select
207
Y.log('multiple select normalization not implemented', 'warn', 'DOM');
208
} else if (node.selectedIndex > -1) {
209
val = Y_DOM.getValue(options[node.selectedIndex]);
216
var addClass, hasClass, removeClass;
220
* Determines whether a DOM element has the given className.
223
* @param {HTMLElement} element The DOM element.
224
* @param {String} className the class name to search for
225
* @return {Boolean} Whether or not the element has the given class.
227
hasClass: function(node, className) {
228
var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');
229
return re.test(node.className);
233
* Adds a class name to a given DOM element.
236
* @param {HTMLElement} element The DOM element.
237
* @param {String} className the class name to add to the class attribute
239
addClass: function(node, className) {
240
if (!Y.DOM.hasClass(node, className)) { // skip if already present
241
node.className = Y.Lang.trim([node.className, className].join(' '));
246
* Removes a class name from a given element.
247
* @method removeClass
249
* @param {HTMLElement} element The DOM element.
250
* @param {String} className the class name to remove from the class attribute
252
removeClass: function(node, className) {
253
if (className && hasClass(node, className)) {
254
node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' +
255
className + '(?:\\s+|$)'), ' '));
257
if ( hasClass(node, className) ) { // in case of multiple adjacent
258
removeClass(node, className);
264
* Replace a class with another class for a given element.
265
* If no oldClassName is present, the newClassName is simply added.
266
* @method replaceClass
268
* @param {HTMLElement} element The DOM element
269
* @param {String} oldClassName the class name to be replaced
270
* @param {String} newClassName the class name that will be replacing the old class name
272
replaceClass: function(node, oldC, newC) {
273
//Y.log('replaceClass replacing ' + oldC + ' with ' + newC, 'info', 'Node');
274
removeClass(node, oldC); // remove first in case oldC === newC
275
addClass(node, newC);
279
* If the className exists on the node it is removed, if it doesn't exist it is added.
280
* @method toggleClass
282
* @param {HTMLElement} element The DOM element
283
* @param {String} className the class name to be toggled
284
* @param {Boolean} addClass optional boolean to indicate whether class
285
* should be added or removed regardless of current state
287
toggleClass: function(node, className, force) {
288
var add = (force !== undefined) ? force :
289
!(hasClass(node, className));
292
addClass(node, className);
294
removeClass(node, className);
299
hasClass = Y.DOM.hasClass;
300
removeClass = Y.DOM.removeClass;
301
addClass = Y.DOM.addClass;
303
var re_tag = /<([a-z]+)/i,
307
addFeature = Y.Features.add,
308
testFeature = Y.Features.test,
312
createFromDIV = function(html, tag) {
313
var div = Y.config.doc.createElement('div'),
316
div.innerHTML = html;
317
if (!div.firstChild || div.firstChild.tagName !== tag.toUpperCase()) {
324
re_tbody = /(?:\/(?:thead|tfoot|tbody|caption|col|colgroup)>)+\s*<tbody/,
326
TABLE_OPEN = '<table>',
327
TABLE_CLOSE = '</table>';
332
_create: function(html, doc, tag) {
335
var frag = Y_DOM._fragClones[tag];
337
frag = frag.cloneNode(false);
339
frag = Y_DOM._fragClones[tag] = doc.createElement(tag);
341
frag.innerHTML = html;
345
_children: function(node, tag) {
347
children = node.children,
352
if (children && children.tags) { // use tags filter when possible
354
children = node.children.tags(tag);
355
} else { // IE leaks comments into children
356
hasComments = children.tags('!').length;
360
if (!children || (!children.tags && tag) || hasComments) {
361
childNodes = children || node.childNodes;
363
while ((child = childNodes[i++])) {
364
if (child.nodeType === 1) {
365
if (!tag || tag === child.tagName) {
366
children.push(child);
372
return children || [];
376
* Creates a new dom node using the provided markup string.
378
* @param {String} html The markup used to create the element
379
* @param {HTMLDocument} doc An optional document context
380
* @return {HTMLElement|DocumentFragment} returns a single HTMLElement
381
* when creating one node, and a documentFragment when creating
384
create: function(html, doc) {
385
if (typeof html === 'string') {
386
html = Y.Lang.trim(html); // match IE which trims whitespace from innerHTML
390
doc = doc || Y.config.doc;
391
var m = re_tag.exec(html),
392
create = Y_DOM._create,
398
if (html != undefined) { // not undefined or null
400
creator = custom[m[1].toLowerCase()];
401
if (typeof creator === 'function') {
408
nodes = create(html, doc, tag).childNodes;
410
if (nodes.length === 1) { // return single node, breaking parentNode ref from "fragment"
411
ret = nodes[0].parentNode.removeChild(nodes[0]);
412
} else if (nodes[0] && nodes[0].className === 'yui3-big-dummy') { // using dummy node to preserve some attributes (e.g. OPTION not selected)
413
if (nodes.length === 2) {
414
ret = nodes[0].nextSibling;
416
nodes[0].parentNode.removeChild(nodes[0]);
417
ret = Y_DOM._nl2frag(nodes, doc);
419
} else { // return multiple nodes as a fragment
420
ret = Y_DOM._nl2frag(nodes, doc);
428
_nl2frag: function(nodes, doc) {
432
if (nodes && (nodes.push || nodes.item) && nodes[0]) {
433
doc = doc || nodes[0].ownerDocument;
434
ret = doc.createDocumentFragment();
436
if (nodes.item) { // convert live list to static array
437
nodes = Y.Array(nodes, 0, true);
440
for (i = 0, len = nodes.length; i < len; i++) {
441
ret.appendChild(nodes[i]);
443
} // else inline with log for minification
448
* Inserts content in a node at the given location
450
* @param {HTMLElement} node The node to insert into
451
* @param {HTMLElement | Array | HTMLCollection} content The content to be inserted
452
* @param {HTMLElement} where Where to insert the content
453
* If no "where" is given, content is appended to the node
454
* Possible values for "where"
456
* <dt>HTMLElement</dt>
457
* <dd>The element to insert before</dd>
459
* <dd>Replaces the existing HTML</dd>
461
* <dd>Inserts before the existing HTML</dd>
463
* <dd>Inserts content before the node</dd>
465
* <dd>Inserts content after the node</dd>
468
addHTML: function(node, content, where) {
469
var nodeParent = node.parentNode,
476
if (content != undefined) { // not null or undefined (maybe 0)
477
if (content.nodeType) { // DOM node, just add it
479
} else if (typeof content == 'string' || typeof content == 'number') {
480
ret = newNode = Y_DOM.create(content);
481
} else if (content[0] && content[0].nodeType) { // array or collection
482
newNode = Y.config.doc.createDocumentFragment();
483
while ((item = content[i++])) {
484
newNode.appendChild(item); // append to fragment for insertion
490
if (newNode && where.parentNode) { // insert regardless of relationship to node
491
where.parentNode.insertBefore(newNode, where);
495
while (node.firstChild) {
496
node.removeChild(node.firstChild);
498
if (newNode) { // allow empty content to clear node
499
node.appendChild(newNode);
504
nodeParent.insertBefore(newNode, node);
509
if (node.nextSibling) { // IE errors if refNode is null
510
nodeParent.insertBefore(newNode, node.nextSibling);
512
nodeParent.appendChild(newNode);
518
node.appendChild(newNode);
522
} else if (newNode) {
523
node.appendChild(newNode);
529
wrap: function(node, html) {
530
var parent = (html && html.nodeType) ? html : Y.DOM.create(html),
531
nodes = parent.getElementsByTagName('*');
534
parent = nodes[nodes.length - 1];
537
if (node.parentNode) {
538
node.parentNode.replaceChild(parent, node);
540
parent.appendChild(node);
543
unwrap: function(node) {
544
var parent = node.parentNode,
545
lastChild = parent.lastChild,
550
grandparent = parent.parentNode;
552
node = parent.firstChild;
553
while (node !== lastChild) {
554
next = node.nextSibling;
555
grandparent.insertBefore(node, parent);
558
grandparent.replaceChild(lastChild, parent);
560
parent.removeChild(node);
566
addFeature('innerhtml', 'table', {
568
var node = Y.config.doc.createElement('table');
570
node.innerHTML = '<tbody></tbody>';
574
return (node.firstChild && node.firstChild.nodeName === 'TBODY');
578
addFeature('innerhtml-div', 'tr', {
580
return createFromDIV('<tr></tr>', 'tr');
584
addFeature('innerhtml-div', 'script', {
586
return createFromDIV('<script></script>', 'script');
590
if (!testFeature('innerhtml', 'table')) {
591
// TODO: thead/tfoot with nested tbody
592
// IE adds TBODY when creating TABLE elements (which may share this impl)
593
creators.tbody = function(html, doc) {
594
var frag = Y_DOM.create(TABLE_OPEN + html + TABLE_CLOSE, doc),
595
tb = Y.DOM._children(frag, 'tbody')[0];
597
if (frag.children.length > 1 && tb && !re_tbody.test(html)) {
598
tb.parentNode.removeChild(tb); // strip extraneous tbody
604
if (!testFeature('innerhtml-div', 'script')) {
605
creators.script = function(html, doc) {
606
var frag = doc.createElement('div');
608
frag.innerHTML = '-' + html;
609
frag.removeChild(frag.firstChild);
613
creators.link = creators.style = creators.script;
616
if (!testFeature('innerhtml-div', 'tr')) {
618
option: function(html, doc) {
619
return Y_DOM.create('<select><option class="yui3-big-dummy" selected></option>' + html + '</select>', doc);
622
tr: function(html, doc) {
623
return Y_DOM.create('<tbody>' + html + '</tbody>', doc);
626
td: function(html, doc) {
627
return Y_DOM.create('<tr>' + html + '</tr>', doc);
630
col: function(html, doc) {
631
return Y_DOM.create('<colgroup>' + html + '</colgroup>', doc);
640
thead: creators.tbody,
641
tfoot: creators.tbody,
642
caption: creators.tbody,
643
colgroup: creators.tbody,
644
optgroup: creators.option
648
Y_DOM.creators = creators;
651
* Sets the width of the element to the given size, regardless
652
* of box model, border, padding, etc.
654
* @param {HTMLElement} element The DOM element.
655
* @param {String|Number} size The pixel height to size to
658
setWidth: function(node, size) {
659
Y.DOM._setSize(node, 'width', size);
663
* Sets the height of the element to the given size, regardless
664
* of box model, border, padding, etc.
666
* @param {HTMLElement} element The DOM element.
667
* @param {String|Number} size The pixel height to size to
670
setHeight: function(node, size) {
671
Y.DOM._setSize(node, 'height', size);
674
_setSize: function(node, prop, val) {
675
val = (val > 0) ? val : 0;
678
node.style[prop] = val + 'px';
679
size = (prop === 'height') ? node.offsetHeight : node.offsetWidth;
682
val = val - (size - val);
688
node.style[prop] = val + 'px';
694
}, '3.5.1' ,{requires:['dom-core']});