欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

小技巧解决“FF不能读取outerHTML”的问题 有大用

shiping1 的头像
对于outerHTML这个DOM属性,在IE/Opera/google Chorme等浏览器中都是可以使用的,但唯独Firefox是不支持的,尽管这个属性平时用的并不多,但有些应用中我们还必须用到,因此很有必要去实现FF下的outerHTML功能。

在网上看了一些文章,最典型的方法应该就是通过defineSetterdefineGetter来为DOM属性扩展这个属性,具体实现即:遍历读取元素的属性及子节点,然后自己拼装html串,具体可以看这篇文章:《firefox没有outerHTML 解决办法》,该文实现了outerHTML的读写,比较完整。

对于获取outerHTML的值,使用拼装HTML串的办法,觉得有点麻烦了,在网上看到一个解决办法,感觉很妙代码也很简洁,而且在各种浏览器中都是可以使用的。其原理为:创建一个div元素,然后将要读取的元素的克隆对象放到这个div中,读取这个div的childNode即可,示例代码如下:
document.createElement("DIV").appendChild(htmlNode.cloneNode(true)).parentNode.innerHTML)document.createElement("DIV").appendChild(htmlNode.cloneNode(true)).parentNode.innerHTML);

来自
http://blog.csdn.net/u011127925/article/details/47150023
 

var htmlString = $('#targetElementId').clone().wrap('<div>').parent().html();

来自 http://www.computerhowtoguy.com/how-to-get-the-outerhtml-of-an-element-using-jquery/


Get selected element's outer HTML

m trying to get the HTML of a selected object with jQuery. I am aware of the .html() function; the issue is that I need the HTML including the selected object (a table row in this case, where .html()only returns the cells inside the row).

I've searched around and found a few very ‘hackish’ type methods of cloning an object, adding it to a newly created div, etc, etc, but this seems really dirty. Is there any better way, or does the new version of jQuery (1.4.2) offer any kind of outerHtml functionality?
 

正确答案
jQuery.fn.outerHTML = function(s) {
    return s
        ? this.before(s).remove()
        : jQuery("<p>").append(this.eq(0).clone()).html();
};

来自 http://stackoverflow.com/questions/2419749/get-selected-elements-outer-html


jQuery: outerHTML

The outerHTML property (IE only) could sometimes be very handy, especially if you’re trying to replace an element entirely. Brandon Aaron has very kindly given us aouterHTML plugin that does half the job as it doesn’t support replacements. The following code snippet fills in the blanks:

jQuery.fn.outerHTML = function(s) {
return (s)
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
}

To get the outerHTML value of an element do this…

$('#myTag').outerHTML();

To replace #myTag entirely do this…

$('#myTag').outerHTML("<p>My brand new #myTag.</p>");

Hope this helps someone :)

来自 http://www.yelotofu.com/2008/08/jquery-outerhtml/

imagine what we have something like this:

<div id="xxx"><p>Hello World</p></div>

if we call .html function in this way:

$("#xxx").html();

we will get:

<p>Hello World</p>

But i need to get:

<div id="xxx"><p>Hello World</p></div>

So, what i need to do? I think to add another wrapper around #xxx, but this is not a good idea.

正确答案 Create a temporary element, then clone() and append():

$('<div>').append($('#xxx').clone()).html();

来自 http://stackoverflow.com/questions/5744207/jquery-outer-html
普通分类: