Search code examples
javascriptcssappendchild

How to add a button in any expected place by using appendChild() function in JavaScript?


I want to add a button in my web page when a certain event is occurred by using javaScript. I searched online much and try to solve this problem by using appendChild() function.

My code is like this :

var btn = document.createElement(‘button’);
btn.body.appendChild(btn);

Here I am facing two problems

  1. My button is added but in a certain corner of my html page and
  2. I can’t add style to this new created button without providing css to other buttons.

So how can I add this button in a certain positon and add css to this button

Thanks in advance.


Solution

    1. Your first problem is you added the button after body. So that your button is appeared in a certain corner of your html page. To solve this problem you may add this after an id containing div. And this div must be in your expected location. Make a div which id is myButton in your expected location

      id="addButton"

    Then append your button after this id like this

    document.getElementById("addButton").appendChild(newButton);
    
    1. To provide CSS to this new created button your CSS code will be like this

      #addButton button {
              display: block;
              background: green;
              padding: 10px;
              color: #ffffff;
          }
      

    To provide the hover effect your code will be

       #addButton button:hover {
                background: red;
            }