/* * @Author: 陶秋峰 * @Date: 2016-01-08 07:49:53 * @Last Modified by: 陶秋峰 * @Last Modified time: 2016-01-08 08:49:57 * @CopyRight 蛮蛮工作室 */ import * as dom from './dom'; import * as dom_construct from './dom-construct'; const force_prop_names = { innerHTML: 1, textContent:1, className: 1, htmlFor: 0, // has("ie"), value: 1 }; const attr_ames = { // original attribute names classname: "class", htmlfor: "for", // for IE tabindex: "tabIndex", readonly: "readOnly" }; const prop_names = { // properties renamed to avoid clashes with reserved words "class": "className", "for": "htmlFor", // properties written as camelCase tabindex: "tabIndex", readonly: "readOnly", colspan: "colSpan", frameborder: "frameBorder", rowspan: "rowSpan", textcontent: "textContent", valuetype: "valueType" }; function get_text(node: HTMLElement): string { let text = ""; let ch = node.childNodes; for(let i = 0, n; n = ch[i]; i++){ if(n.nodeType != 8){ if(n.nodeType == 1){ text += get_text(n); }else{ text += n.nodeValue; } } } return text; } function has_attr(node: HTMLElement, name: string): boolean { let attr = node.getAttributeNode && node.getAttributeNode(name); return !!attr && attr.specified; // Boolean } export function get(node: string | HTMLElement, name: string): string { let el = dom.by_id(node); let lc = name.toLowerCase(); let prop_name = prop_names[lc] || name; let force_prop = force_prop_names[prop_name]; let value = el[prop_name]; // should we access this attribute via a property or via getAttribute()? if(force_prop || typeof value != "undefined"){ // node's property return value; // Anything } if(prop_name == "textContent"){ return get_text(el); } let attrName = attr_ames[lc] || name; return has_attr(el, attrName) ? el.getAttribute(attrName) : null; // Anything } export function has(node: string | HTMLElement, name: string): boolean { let lc = name.toLowerCase(); return force_prop_names[prop_names[lc] || name] || has_attr(dom.by_id(node), attr_ames[lc] || name); // Boolean } export function set(node: string | HTMLElement, name: string, value: any): HTMLElement { let el = dom.by_id(node); let lc = name.toLowerCase(); let prop_name = prop_names[lc] || name; let force_prop = force_prop_names[prop_name]; if (prop_name === 'innerHTML'){ dom_construct.empty(el); el[prop_name] = value; return el; } else if (prop_name === 'textContent') { dom_construct.empty(el); el.appendChild(el.ownerDocument.createTextNode(value)); return el; } else if (force_prop) { el[prop_name] = value; } else { // node's attribute el.setAttribute(attr_ames[lc] || name, value); } return el; // DomNode } export function remove(node: string | HTMLElement, name: string): void { let el = dom.by_id(node); el && el.removeAttribute(attr_ames[name.toLowerCase()] || name); };