2009-12-16 61 views
3

例如,如果我有HTML ul列表像如何獲取使用jquery的子標記和父標記的html字符串?

<ul id="ulIdentificator"> 
    <li id="li0"></li> 
    <li id="li1"></li> 
    <li id="li2"><label id="label1"></label></li> 
</ul> 

如果我使用jQuery這樣

var htmlStr = $("#li2").html(); 

其結果將是一個包含標籤標記<LABEL id="label1"></LABEL></li>我需要得到一個包含HTML字符串只有字符串<LI id="li2"><LABEL id="label1"></LABEL></LI>

+1

下一個jquery問題後,你是http://stackoverflow.com/questions/1917040/can-i-get-the-full-html-represenation-of-an-htmlelment-dom-object – 2009-12-16 20:49:27

回答

6

second OuterHTML technique Andres提到(來自Web架構師的博客)適用於所有瀏覽器,因此它可能是更好的選擇。其基本思想是,你可以通過它的另一個元素的innerHTML獲取元素的外部HTML:

var outerHtml = $("<div/>").append($("#li2").clone()).html(); 

這裏只有一個稍微有點棘手 - 確保clone原來的元素,這樣你就不會從刪除DOM。

如果你經常這樣做,或者想對元素數組做這樣的事情,可能值得跟隨鏈接的例子,並做一個小插件來做到這一點。

+1

+1非常好的答案。但在[這個其他問題](http://stackoverflow.com/questions/995760/in-jquery-are-there-any-function-that-similar-to-html-or-text-but-return-the/ 5314397#5314397)你有你的同樣的技術,也有一個** IFrames **問題的解決方案。 – 2011-03-15 17:42:47

0
+3

OuterHTML II技術非常簡單,值得在你的答案中複製。 – 2009-12-16 19:44:42

+0

好的,這是正確的答案,但我會接受它,如果你添加一些例子不只是2個鏈接,其他SO人在這裏看到它。 – nemke 2009-12-16 20:23:13

1

你也可以寫與提出的方法一個小的jQuery插件傑夫胸骨:

// jQuery plugin 'htmlWithParent' 

jQuery(function($) { 

    $.fn.htmlWithParent = function() { return $j("<div/>").append($j(this).clone()).html(); }; 

});

,並使用這個小插件對自定義,例如:

var htmlCode = $("<p><span>Helo world!</span></p>"); 

// Return only child nodes: <span>Helo world!</span> 
var output1 = $(htmlCode).html(); 

// Return whole HTML code (childs + parent): <p><span>Helo world!</span></p> 
var output2 = $(htmlCode).htmlWithParent();

非常有用的方法。 ;)

+1

不錯的工作,值得一票:) – nemke 2012-01-11 11:38:30

+0

謝謝。 ;)我總是製作小的自定義jQuery插件。代碼越少,透明度越高。 – 2012-01-11 11:52:38