1

I'm trying to get JavaScript's document.write to work like PHP's echo. For example:

<?php

echo "
<style>
div {
border: 1px solid black;
}
<style>
";

?>

<div> Hello </div>

would work just fine in PHP, and it'll make a border of 1px solid black around the div. However in JavaScript:

<script>

document.write("
<style>
div {
border: 1px solid red;
}
<style>
");

</script>

<div> Hello </div>

it wouldn't work, and it doesn't make a border of 1px solid black around the div. I'm wondering if it's even possible to do the same thing with JavaScript, and if so what am I doing wrong and how to fix it.

Tom Fenech
  • 65,210
  • 10
  • 85
  • 122
frosty
  • 2,250
  • 7
  • 23
  • 61

2 Answers2

3

I see two errors in your javascript code. The first, You can't use new lines in your code. It needs to be all over one line or concatenated by ending the string then using a + on the next line.

You also aren't closing your style tag, which was disrupting the final output.

The following code works for me:

<script type="text/javascript">

document.write("<style>div {border: 1px solid red;}</style>");

</script>

<div> Hello </div>

Or, as mentioned above with the string concatenation:

<script>

document.write(
    "<style>"
    +"div {"
    +"border: 1px solid red;"
    +"}"
    +"</style>"
);

</script>

<div> Hello </div>
Samuel Cook
  • 15,511
  • 6
  • 43
  • 58
2

Just create the styleless div like this:

<div id="box1"></div>

And then you can manipulate the styling with js like this:

document.getElementById('box1').style.cssText = 'background-color:black;height:50px;';

With jQuery, it's even easier:

HTML:

<div id="box1"></div>

jQuery:

$("#box1").css("background-color", "black");
AndrewL64
  • 13,967
  • 6
  • 36
  • 64