Mandatory vanilla response. It may not be shorter, but faster.
Get an element, capture all subelements using the "test" class, create your div, check the length of the subelements, and if the length is true, set innerHTMLto div. Else, add it.
var el = document.getElementById("something");
var subel = el.getElementsByClassName("test");
var div = document.createElement("div");
div.className = "test"
if (subel.length) {
div.textContent = "somenewcontent";
while(el.hasChildNodes()) el.removeChild(el.lastChild);
el.appendChild(div);
} else {
div.textContent = "somecontent";
el.appendChild(div);
}
source
share