Edin Puzic
Edin Puzic

Reputation: 1048

Append div in button on click Javascript

Hi how to append div inside button on click this is my JavaScript:

function addLoader() {
    var div = document.createElement('div');
    div.innerHTML = '<div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div>';
    var test01 = document.createElement('button');
    test01.appendChild(div);
    console.log(test01);
}

I want to add innerHTML inside button tags on click

<button onclick="addLoader(this);">testt </button>

It must be like this when function is finish :

<button>testt <div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div> </button>

Upvotes: 0

Views: 3221

Answers (3)

brk
brk

Reputation: 50291

HTML

// Added id attribute
<button onclick="addLoader();" id = "test01">testt </button>

JS

function addLoader() {
    var _div = document.createElement('div');
    _div.innerHTML = '<div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div>';
    //append _div to button
    document.getElementById("test01").appendChild(_div);

}

Working jsfiddle

Snapshot EDIT

This will append element to any button call addLoader on click

function addLoader(elem) {
        var _div = document.createElement('div');
        _div.innerHTML = '<div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div>';
        elem.appendChild(_div);
    }

Updated jsfiddle

Upvotes: 1

0xdw
0xdw

Reputation: 3842

var btn = document.getElementById("addLoader");

if (btn) {
  btn.addEventListener('click', addLoader, false);
}

function addLoader() {
  var div = document.createElement('div');
  div.innerHTML = '<div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div>';
  this.appendChild(div);
}
<button id="addLoader">Test</button>

Upvotes: 1

Rob Brander
Rob Brander

Reputation: 3771

You just need one more line of code. The variable test01 is created in memory but not added to the DOM. You must append this new element to the DOM (ie. document.appendChild(test01))

Upvotes: 0

Related Questions