2015-11-12 33 views
0

我想在HTML註釋之前插入div與iframe(它是這個位置唯一的唯一元素)。在HTML註釋之前插入DIV元素

所以我有這樣的評論:<!-- Comment -->,我想在評論之前,這樣的插入代碼:

<div id="test"> 
    <noscript> 
     <iframe src="https://test.net" frameborder="0" scrolling="no" width="742" height="92"></iframe> 
    </noscript> 
</div> 

我試着像.append()的方法和前置(),但沒有成功。

結果應該是:

<div id="test"> 
     <noscript> 
      <iframe src="https://test.net" frameborder="0" scrolling="no" width="742" height="92"></iframe> 
     </noscript> 
    </div> 
<!-- Comment --> 

任何幫助,非常感謝!

+2

@Duane of course您可以選擇一個評論! – void

回答

0

嘗試使用.filter()回報元素,其中nodeType8

var div = "<div>abc</div>"; 
 

 
var comment = $("body").contents().filter(function() { 
 
    return this.nodeType === 8 
 
}); 
 

 
$(div).insertBefore(comment);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<body> 
 
<!-- Comment --> 
 
    </body>

0

HTML註釋具有在DOM層次結構中的節點,它的nodeType屬性是8

$(document).ready(function() { 
    var _html = '<div id="test">' 
    + '<noscript>' 
    + '<iframe src="https://test.net" frameborder="0" scrolling="no" width="742" height="92"></iframe>' 
    + '</noscript>' 
    + '</div>'; 

    $('body').contents().each(function (i, elem) { 
     if (elem.nodeType == 8 && elem.data == " Comment ") { 
      $(_html).insertBefore(elem); 
     } 
    }); 

}); 

所以通過所有穿越評論找到你想要的並在該評論節點之前插入HTML。

工作fiddle