-1

Today I'm learning bootstrap 3 for the first time. I successfully apply a class for my button element. I used event handler to create more buttons on click with createElement() method. In these newly created buttons, however, I failed to apply the the same class. Is the button created with createElement() method different from button originally in the body?

Here is the link to CodePen: https://codepen.io/bqw5354/pen/abZPRYm

<html lang="en">
    <head>
        <title>Bootstrap Button</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    </head>
    <body>
        <button type="button" id="button1" class="btn-primary">1st</button>
        <script>
            document.getElementById("button1").addEventListener("click", function(){
            var btn = document.createElement("button");
                btn.id = "button2"                    
                btn.class = "btn-primary";
                btn.innerHTML = "2nd";
                document.body.appendChild(btn); 
                document.getElementById("button2").addEventListener("click", function(){
                    var btn = document.createElement("button");
                    btn.id = "button3"                    
                    btn.class = "btn-primary";
                    btn.innerHTML = "3nd";
                    document.body.appendChild(btn);
                })
            })
      </script>
    </body>
</html>
LamberWBY
  • 1
  • 1
  • One problem that I noticed is that you use the same id for these new buttons. – react_or_angluar Nov 13 '20 at 00:15
  • Your question can be reduced to: "How can I add a class to a DOM element in JavaScript?" which is answered [here](https://stackoverflow.com/questions/1115310/how-can-i-add-a-class-to-a-dom-element-in-javascript) – Remy Nov 13 '20 at 00:43
  • Thank you. I didn't realize that class was not added at all as console reported no error. – LamberWBY Nov 13 '20 at 14:50

1 Answers1

1

Use btn.className instead of btn.class

It will work!

Vasilis S
  • 51
  • 1
  • 2
  • 5