Inserting HTML using JavaScript

Ok, I read this thread to figure out how to generate HTML with JavaScript. I attempted doing it with the following script:

<script type='text/javascript'>
function generate_page() {
    var x = 0;
    var y = 0;
    var lines = 20;
    var output;
    while (x < lines) {
        while( y < lines*2){
            output = ("<div id='x" + x + "_" + y + "'>x</span>");
            $('board').prepend(output);
            y++;
        }
        y = 0;
        x++;
        $('board').append('<br />');
    }
}
</script>

</head>
<input type='button' value='test' onClick='generate_page()'>
<body>
<div id='board'>

</div>

</body>
</html>

It doesn't return any errors but just simply doesn't do anything. What am I doing wrong?

Answers


You are missing the # sign for the ids, try this:

<script type='text/javascript'>
function generate_page() {
    var x = 0;
    var y = 0;
    var lines = 20;
    var output;
    while (x < lines) {
        while( y < lines*2){
            output = ("<span id='x" + x + "_" + y + "'>x</span>");
            $('#board').prepend(output);
            y++;
        }
        y = 0;
        x++;
        $('#board').append('<br />');
    }
}
</script>

</head>

<body>
<input type='button' value='test' onClick='generate_page()'>
<div id='board'>

</div>

</body>
</html>

also move the button to the body.


You're opening a DIV tag and closing a SPAN tag in your JavaScript.


You are opening a div and closing it with a span, also, you never close the div, and never actually open the span. By the way, utilizing document.createElement("div") is a clean way to do this.


you're using jQuery syntax so you should includ jQuery

like this:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type='text/javascript'>
    function generate_page() {
        var x = 0;
        var y = 0;
        var lines = 20;
        var output;
        while (x < lines) {
            while (y < lines * 2) {
                output = ("<div id='x" + x + "_" + y + "'>x</span>");
                $('#board').prepend(output);
                y++;
            }
            y = 0;
            x++;
            $('#board').append('<br />');
        }
    } 
</script></head><body>
<input type='button' value='test' onclick='generate_page()'>
<div id='board'>
</div></body></html>

Need Your Help

Can a C# Interface require or dictate a specific class?

c# interface constraints

Can I declare an Interface (i.e. IMySpecialControl) that requires classes implementing it to also inherit from some base class (i.e. System.Windows.Controls.UserControl)?

Detecting Adobe Reader in ie11 with JavaScript

javascript detect acrobat internet-explorer-11

I am trying to detect the Adobe Reader plugin for IE11, but for some reason it always returns null. I am lead to believe it is because IE11 doesn't use the same plugin name as older versions of Int...