- 假设要获取<p id="outerID">sdfdsdfsd</p> 的 P的outerHTML
- 代码:
- var _p = document.getElementById('outerID');
- _P = _P.cloneNode();
- var _DIV = document.createElement();
- _DIV.appendChild(_P);
- alert(_DIV.innerHTML); 就是P的outerHTML;
复制代码 但这样做局限性很大,只能针对这一个标签进行操作。不方便多次使用。为了解决这个问题,我们只有用DOM原型扩展方法解决- if(typeof(HTMLElement)!="undefined" && !window.opera)
- {
- HTMLElement.prototype.__defineGetter__("outerHTML",function()
- {
- var a=this.attributes, str="<"+this.tagName, i=0;for(;i<a.length;i++)
- if(a[i].specified)
- str+=" "+a[i].name+'="'+a[i].value+'"';
- if(!this.canHaveChildren)
- return str+" />";
- return str+">"+this.innerHTML+"</"+this.tagName+">";
- });
- HTMLElement.prototype.__defineSetter__("outerHTML",function(s)
- {
- var r = this.ownerDocument.createRange();
- r.setStartBefore(this);
- var df = r.createContextualFragment(s);
- this.parentNode.replaceChild(df, this);
- return s;
- });
- HTMLElement.prototype.__defineGetter__("canHaveChildren",function()
- {
- return !/^(area|base|basefont|col|frame|hr|img|br|input|isindex|link|meta|param)$/.test(this.tagName.toLowerCase());
- });
- }
复制代码 |