最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery append not working(adding css to head) - Stack Overflow

programmeradmin3浏览0评论

I want to add a stylesheet to the head of a page, but for some reason it doesn't work. Should i use something else, instead of append?

the code

$('head').append('<link rel="stylesheet" href="test.css" type="text/css" class="test" />');

maybe some usefull info, i am using firefox 3.6.17

I want to add a stylesheet to the head of a page, but for some reason it doesn't work. Should i use something else, instead of append?

the code

$('head').append('<link rel="stylesheet" href="test.css" type="text/css" class="test" />');

maybe some usefull info, i am using firefox 3.6.17

Share Improve this question edited Jun 16, 2011 at 19:35 user759235 asked Jun 16, 2011 at 19:29 user759235user759235 2,2073 gold badges42 silver badges85 bronze badges 6
  • if you are adding html, use $('head').html("<link rel="stylesheet" href="test.css" type="text/css" class="test" />"); - api.jquery./html – John Commented Jun 16, 2011 at 19:31
  • This should work - are you wrapping it in $(function(){}); ? – kinakuta Commented Jun 16, 2011 at 19:33
  • No, using html will remove all other code inside the head. – user759235 Commented Jun 16, 2011 at 19:33
  • @John No, that will replace the content of head. @user759235 Your code seems to work to me. – lonesomeday Commented Jun 16, 2011 at 19:34
  • its used inside an plugin, but i have tried it on several places, with no result – user759235 Commented Jun 16, 2011 at 19:34
 |  Show 1 more ment

4 Answers 4

Reset to default 6

You could try something like this:

loadcss = document.createElement('link');
loadcss.setAttribute("rel", "stylesheet");
loadcss.setAttribute("type", "text/css");
loadcss.setAttribute("href", "test.css");
document.getElementsByTagName("head")[0].appendChild(loadcss);

You could do

jQuery(document.head).append('<link rel="stylesheet" href="test.css" type="text/css" class="test" />');

You should put that code in the document ready, in order to have the DOM loaded. Are you? And then something like:

$(document).ready( function() {
  $("head").append("<link>");
  css = $("head").children(":last");
  css.attr({
    rel:  "stylesheet",
    type: "text/css",
    href: "test.css"
  });
});

try:

$(document).ready( function() {

    $("head").append("<link>");
    var css = $("head").children(":last");
    css.attr({
      rel:  "stylesheet",
      type: "text/css",
      href: "test.css"
    });

});

example is on: http://jsfiddle/XjAu4/

发布评论

评论列表(0)

  1. 暂无评论