Polly
Polly

Reputation: 657

I need to put a variabile in a <style> tag

Suppose to have this tag:

var variabile_colore="#efdcdc";

I need to put a variable in a tag (I think something like this but it not work) :

<style>.foot {color: variabile_colore;} </style>

Anyone can help me?

Upvotes: 1

Views: 86

Answers (7)

hr_117
hr_117

Reputation: 9627

Because for me it looks like you try to generate a css class from JavaScript. Have a look to this answer.

Here the adaption to your case (not tested):

var variabile_colore="#efdcdc";

$("<style type='text/css'> .foot{ color:" +  variabile_colore + 
               "; } </style>" ).appendTo("head");

Upvotes: 0

Ehsan
Ehsan

Reputation: 12959

this help you :

<body>
       <div class="foot" id="foot">Sample Text</div>
      <script>
          var variabile_colore="#efdcdc";
          var x = document.getElementById("foot");
          x.style.color = variabile_colore;   
       </script>
</body>

Upvotes: 0

Rayon
Rayon

Reputation: 36609

You can create dynamic style tag using createElement and append it in DOM

$('#btn').on('click', function() {
  var sheet = document.createElement('style');
  var color = 'red';
  sheet.innerHTML = "p {color:" + color + "}";
  document.body.appendChild(sheet);
})
p {
  color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p>Hello p tag</p>
<button id='btn'>Change</button>

Upvotes: 1

Paresh Barad
Paresh Barad

Reputation: 1609

I think you need to apply color property forcefully.

Please try with following.

var variabile_colore = "#efdcdc !important";
$('.foot').css('color', variabile_colore);

Upvotes: 3

brk
brk

Reputation: 50326

I need to put a variable in a tag (I think something like this but it not work) :

Not sure what exactly it mean Did you mean to create a style tag using js and put declaration in it?

If so then

var css= '.foot {color: "#efdcdc";}',
    head = document.head || document.getElementsByTagName('head')[0],
    style = document.createElement('style');
    style.type = 'text/css';
    if (style.styleSheet){
       style.styleSheet.cssText = css;
    } else {
      style.appendChild(document.createTextNode(css));
    }
    head.appendChild(style);

If style is already present in stylesheet

$("#elementId").addClass('foot');

If you want to add inline css

$('.foot').css('color', variabile_colore);

Upvotes: 1

BenG
BenG

Reputation: 15154

use jQuery:-

$('.foot').css('color', variabile_colore);

Upvotes: 1

chandresh_cool
chandresh_cool

Reputation: 11830

Instead of this you can use DOM objects of javascript by creating an id on style tag :

document.getelementbyId('styleid').style.color = "#efdcdc";

Upvotes: 2

Related Questions