jQuery: 取得元素完整的 html 字串

這篇的小技巧來自這裡:
http://jquery-howto.blogspot.com/2009/02/how-to-get-full-html-string-including.html
假設有一段 html 如下:

<div class='level-1'>
  <div class='level-2'>Item1</div>
  <div class='level-2'>Item2</div>
<div>

由於 jQuery 提供的 html() 方法是使用 innerHtml, 因此呼叫 $(‘div.level-1’).html() 會得到這個:

<div class="level-2">Item1</div>
<div class="level-2">Item2</div>

不過我們想要得到的是包含 level-1 的上一層怎麼辦 ? 可以用下列的小技巧:

var html = $('<div>').append($('div.level-1').clone()).remove().html();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s