Mujtaba Hussain Bhat Mujtaba Hussain Bhat - 9 months ago 26
Javascript Question

Trying add a div dynamically with giving class inside a div

i was trying to create a div dynamically by using js method createElement() in which i am giving a class but is not working

HTML code

<body>
<p>Click the button to make a BUTTON element.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
var btn = document.createElement('<div class="test"></div>');
document.body.appendChild(btn);
}
</script>



Answer Source

I think you want something like this:

function myFunction() {
    var btn = document.createElement('div');
    btn.classList.add('test');
    document.body.appendChild(btn);
}