user4540007
user4540007

Reputation:

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 -->"));

Upvotes: 3

Views: 689

Answers (1)

mplungjan
mplungjan

Reputation: 177692

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)

Upvotes: 1

Related Questions