const div = document.createElement('div');
div.setAttribute('id', 'my-div');
div.className = 'my-class';
document.body.appendChild(div);
// or use any other container instead of body
document.querySelector('#element-with-id').appendChild(div);
Clear the div’s contents:
div.innerHTML = '' – clears all content
div.textContent = '' – safer if just textdiv.replaceChildren() – modern & clean