String construction with document.write Javascript

advertisements

I am trying to write a div element from javascript. I want the line written as follows, using document.write():

<div class="Square15px" onmouseover="changeColor('boxid')"></div>

I call the function that writes the div element with:

<script type="text/javascript">
      colorPicker("box1");
 </script>

I have tried the document.write() method, building the string several different ways such as:

function colorPicker(box) {
    var box = document.getElementById(box);
    var boxid = box.id;
    var AquaStr1 = '<div class="AquaSquare15px" onmouseover="changeColor("';
    var AquaStr2 = '")></div>';

    var AquaString = AquaStr1.concat(boxid, AquaStr2);
    document.writeln(AquaString);
}

I have also tried splitting up the string many different ways using + as concat operator. The string builds incorrectly at the end of boxid. I get the same result no matter how I write the code block:

<div class="AquaSquare15px" onmouseover="changeColor(" box1?)=""/>

I just can't seem to see my error here, I have reviewed all of the help I can find. With the exception of the space between the quote and box1, everything is correct up until the mysterious question mark. I reviewed the results from IE9 developer tool (F12). I am not an experienced programmer, so I suspect I am in error somehow.


As pointed out in the comments section: you shouldn't use document.write. But nevertheless, your string concatenation went wrong. Try this instead:

function colorPicker(box) {
    var boxid = document.getElementById(box).id;
    var aquaStr = '<div class="AquaSquare15px" onmouseover="changeColor(\''+boxid+'\')"></div>';

    document.writeln(aquaStr);
}