Search code examples
jqueryhtmlappendcommentsinsertafter

jQuery insert html after comment tag


How do insert html after <!-- example comment --> in head document. For example I want to append css in head section with jquery after specific comment tag.

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

Solution

  • Using the code from 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)