0

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>

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Can I do this without using any ID class? just button tag?
You can do that but it will be complex, reason is there can be multiple button in your page. Do you want to add same DOM element inside other button also?
Yes but jos on buttons that have onclick function
@EdinPuzic updated the answer.Please check updated jsfiddle
1

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>

Comments

0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.