I have a Element, that looks like this:
<div id="test">
<span>You have
<em>30</em>
<span> characters left</span>
</div>
and I want to replace it either with:
<div id="test">
<span>You reached the maximum length</span>
</div>
or with
<div id="test">
<span>Your text is </span>
<em>30</em>
<span> characters to long</span>
</div>
Is there a way to replace all child elements with the set of new elements?
At the Moment I’m using to following function to remove all elements first:
function emptyElement(id) {
while(document.getElementById(id).hasChildNodes()) {
document.getElementById(id).removeChild(document.getElementById(id).firstChild)
}
}
Afterwards I’m adding content again:
span1 = document.createElement("span");
span1.appendChild(document.createTextNode("You have "));
len = document.createElement("em");
len.appendChild(document.createTextNode(length));
span2 = document.createElement("span");
span2.appendChild(document.createTextNode(" characters left."));
// remove child elements
emptyElement('test');
// Add content
document.getElementById('test').appendChild(span1);
document.getElementById('test').appendChild(len);
document.getElementById('test').appendChild(span2);
I have the impression that there might be an easier way for (1) removing the child-elements, (2) generationg the content and (3) adding the new elemnts to the div.
element.innerHTML = '';.innerHTML, or caching a collection of elements.or
elem.parentNode.replaceChild(new_elem, elem);on the#testelement will be the easiest way.Using cached DOM elements
Demo: http://jsfiddle.net/aKASN/1/
HTML:
JavaScript:
Using hidden elements (recommended)
Another method, which I recommend over the previous ones, is to have all elements in the and hide the unused messages using a CSS. This is more efficient than DOM manipulation, because the elements don’t have to be created over and over again.
Demo: http://jsfiddle.net/aKASN/
CSS:
HTML:
JavaScript: