Inserting css with javascript conditions

Discussion in 'JavaScript' started by News Updates, Jan 30, 2012.

  1. #1
    Hi friends,

    Im trying to insert css with javascript in a static page.

    I want a certain piece of css on my specific category page, eg category is "Marketing"
    I want javascript to check my category and add css. eg if category is marking then it should add the my "internal css" in page code

    while google around I found it. Its not the exact code but It may can help you to help me.. but the javascript condtional funtion is missing


    function injectCSS() {
        var headTag = document.getElementsByTagName("head")[0].innerHTML;	
    	var newCSS = headTag + '<style type="text/css">*insert CSS here*</style>';
    	document.getElementsByTagName('head')[0].innerHTML += newCSS;
     }
    Code (markup):
     
    News Updates, Jan 30, 2012 IP
  2. JohnnySchultz

    JohnnySchultz Peon

    Messages:
    277
    Likes Received:
    4
    Best Answers:
    7
    Trophy Points:
    0
    #2
    how do you plan to check what is the category of your page?
     
    JohnnySchultz, Jan 31, 2012 IP
  3. rainborick

    rainborick Well-Known Member

    Messages:
    424
    Likes Received:
    33
    Best Answers:
    0
    Trophy Points:
    120
    #3
    rainborick, Jan 31, 2012 IP
  4. JohnnySchultz

    JohnnySchultz Peon

    Messages:
    277
    Likes Received:
    4
    Best Answers:
    7
    Trophy Points:
    0
    #4
    your right but creating a style tag and append it to the <body> would do, right?
     
    JohnnySchultz, Feb 2, 2012 IP
  5. rainborick

    rainborick Well-Known Member

    Messages:
    424
    Likes Received:
    33
    Best Answers:
    0
    Trophy Points:
    120
    #5
    Not necessarily. Some browsers might recognize a <style> tag in the <body> because they try to be very tolerant of HTML errors, but technically, the <style> tag should only appear in the <head> and browsers are free to ignore it. As long as you're using JavaScript to do this, do it the way I suggested. It's easier, the code I wrote gives you functions you can call that make it dirt simple, and it's much more reliable because you're doing it the right way.
     
    rainborick, Feb 2, 2012 IP