-1

I have been writing a javascript code that creates a button. But I'm unable to attach event handler to buttons. When I try to get child, it returns undefined. There are two functions, one creates button when window loads and other function tries to get the children.

window.onload = function ()
        {
            f1();
            reader();
        }
       function f1()
       {
        var x = document.getElementById("buttons");
        for(var i=9;i>=0;i--)
        {
            
            var y = document.createElement("BUTTON");
            y.setAttribute("class","btn btn-primary btn-lg");
            y.setAttribute("id","mybtn");
            var z = document.createTextNode(i);
            
             y.appendChild(z);
            x.appendChild(y);
            
        }
       function reader()
        {
            var x = document.getElementById("mybtn").firstChild;
            alert(x);
            
        }
<div id="stage">
            <div id="screen">
                
                
            </div>
            <div id="buttons">
                
                
            </div>
            <div id="sb">
                
                
            </div>
            
        </div>
Dani Vijay
  • 1,478
  • 1
  • 14
  • 32
Naveed Khan
  • 75
  • 1
  • 15
  • Where's your code that tries to attach an event handler? Your code does not show what the title asks. – jfriend00 Dec 16 '15 at 03:12
  • Also, you cannot have multiple DOM objects with the same id value. You are attempting to create 10 objects all with `id="mybtn"`. – jfriend00 Dec 16 '15 at 03:13
  • i am trying to get all objects by child[0] but it returns undefined – Naveed Khan Dec 16 '15 at 04:33
  • Please show us the EXACT code that fails. So far, you've shown a bunch of code and described a problem that is NOT illustrated by the code. The fastest way to get help is to show the exact code you're using, describe what doesn't work, what you see in the debug console what you're trying to accomplish and what you expect the result to be. – jfriend00 Dec 16 '15 at 04:45

1 Answers1

0

You are missing } end of f1 function

 function f1()
 {
    var x = document.getElementById("buttons");
    for(var i=9;i>=0;i--)
    {

        var y = document.createElement("BUTTON");
        y.setAttribute("class","btn btn-primary btn-lg");
        y.setAttribute("id","mybtn");
        var z = document.createTextNode(i);

         y.appendChild(z);
        x.appendChild(y);

    }
 }
 function reader()
 {
        var x = document.getElementById("mybtn").firstChild;
        alert(x);

 }
dieuvn3b
  • 4,548
  • 2
  • 14
  • 26