Hassan
Hassan

Reputation: 356

How to use variable in js using style tag

How can I use javascript variable in style tag? I tried with jQuery:

var height = $('.replyComment').height();
$('div.replyComment').append('<style>div.replyComment:before{content: ""; border-left: 1px solid #e1e1e1;position:absolute; left:38px; top:-20px; height:'+ height +';}</style>');

So where am I wrong? What I have to do to assign height of a div in div:before using height variable?

Upvotes: 1

Views: 1339

Answers (4)

Eloy Pineda
Eloy Pineda

Reputation: 2187

From jQuery documentation you can see how you can use the height(), not only to get the height of an element, but to set it too. Just pass the new height as an argument: .height(value)

Beside that. It is not a good practice to set inline css styles. I rather use jQuery.addClass() and jQuery.removeClass() functions from jQuery to change the styling of an HTML element.

For your example it will look something like this:

css

.styles-to-add:before{
  content: ""; 
  border-left: 1px solid #e1e1e1; 
  position: absolute; 
  left: 38px; 
  top: -20px; 
}

javascript

$('div.replyComment').addClass('styles-to-add');

And then independently you can set the height of any element like:

var height = $('.replyComment').height();
$('div.replyComment:before').height(height);

Upvotes: 0

Shrinivas Pai
Shrinivas Pai

Reputation: 7701

Try to append it to head.

$('head').append('<style>div.replyComment:before{content: ""; border-left: 1px solid #e1e1e1;position:absolute; left:38px; top:-20px; height:'+ height +'px;}</style>');

Make sure that you have to add px to height.

Upvotes: 3

kwh71787
kwh71787

Reputation: 576

Try this instead.

jQuery('div.replyComment').css('height', height);

div.replyComment:before{
    content: ""; 
    border-left: 1px solid #e1e1e1; 
    position:absolute; 
    left:38px; 
    top:-20px; 
}

Add the css to your style sheet, then target the div height specifically when needed.

Upvotes: 0

Aziz
Aziz

Reputation: 7783

You can use jQuery's CSS function

css({"propertyname":"value","propertyname":"value",...});

Like that:

var height = jQuery('.replyComment').height();

jQuery('div.replyComment:before').css({
  "content":"",
  "border-left":"1px solid #e1e1e1",
  "position":"absolute",
  "left":"38px",
  "top":"-20px",
  "height": height
});

More info: jQuery Docs, W3Schools

Upvotes: 0

Related Questions