jQuery在注释标记后插入html

时间:2015-12-13 06:59:54

标签: jquery html append comments insertafter

如何在头文档中的<!-- example comment -->之后插入html。例如,我想在特定注释标记之后使用jquery在头部中追加css。

$('<link>', {
    rel: 'stylesheet',
     href: url
 }).appendTo($("<!-- Related css to this page -->"));

1 个答案:

答案 0 :(得分:1)

使用selecting html comments with jquery

中的代码
var url ="bla.css";
$(function() {
  $("head").contents().filter(function() {
    return this.nodeType == 8;
  }).each(function(i, e) {
    if ($.trim(e.nodeValue) == "Related css to this page") {
      $('<link>', {
        rel: 'stylesheet',
        href: url
      }).insertAfter(e);
      return false; // stop immediately - remove if f.ex. url is an array of css
    }
  });
});

FIDDLE (which is using body since head is inserted by JSFiddle)