When working with DOM objects, it is often related to the operation of their properties, in order to improve development efficiency, while taking into account the performance of the browser, in this simple encapsulation of a few common properties. Because it is modular, in this just introduced a part of the code, the other code in the previous module package has written. If there are deficiencies, million hope to put forward, thank you! 1, determine whether there are attributes, and set the operation of the property
YY.fn.extend ({attr:function(attname,attvalue) {//determines if an incoming parameter has a property value and does not return the property name directly if(Arguments.length = = 1){ return This[0].attname; }Else{ //If an attribute value is passed in, the attribute value is added to the attribute return This. each (function(){ This. AttName =Attvalue; }); }} })
2. Pre-Set Value Val method
YY.fn.extend ({val:function(value) {//determine if value has values, no returns, value is set if(Value = = =undefined) { return This[0].value; }Else{ return This[0].each (function(){ This. Value =value; }) } } });
3. Returns or sets the content HTML method of the selected element
YY.fn.extend ({html:function(HTML) {if(html = = =undefined) { //returns the InnerHTML of the 0 element return This[0].innerhtml; } Else { //set all the InnerHTML return This. each (function () { This. InnerHTML =html; }); } } });
4. Set or return the text content of the selected element text method
YY.fn.extend ({text:function(text) {if(Text = =undefined) { return This[0].innertext; }Else{ return This. each (function(){ This. innerText = text;//the early Firefox browser does not support innertext }) } } })
Compatible with the low-version Firefox browser wording
Yy.extend ({//Get innerHTML valueGetinnertext:function(DOM) {varList = []; if(Dom.innertext!==undefined) { returnDom.innertext; } Else{gettextnode (DOM, list); //swap an array to a string returnList.join (' ' ); } functionGettextnode (DOM, arr) {//put all the text nodes inside the DOM into arr varI, L =dom.childNodes.length, node; for(i = 0; i < l; i++) {node=dom.childnodes[i]; if(Node.nodetype = = 3 ) { //the text value of the Node.nodevalue nodeArr.push (Node.nodevalue); } Else{gettextnode (node, arr);//Recursive processing Method } } } }, //Setting the innerHTML valueSetinnertext:function(dom,str) {//determine if the browser supports innertext if(' InnerText 'inchDOM) {Dom.innertext=str; }Else{dom.innerhtml= ' '; //Creating a text node directly on-premises is not supporteddom.appendchild (document.createTextNode (str)); } } });
Then the corresponding test method should be changed to
YY.fn.extend ({text:function(text) {if(Text = =undefined) { //returns the InnerHTML of the 0 element returnYy.getinnertext ( This[0 ] ); } Else { //set all the InnerHTML return This. each (function() {Yy.setinnertext ( This, text); }); } } });
About the attribute operation of JS Encapsulation Framework class Library