Write messages on the page instead of using alert boxes (Part II)
The folowing function uses DOM-2 to create a div tag dynamically and append messages.
function appendText(vText){ var eldiv = document.getElementById('msg'); if(!eldiv){ var rdiv = document.createElement("div"); rdiv.style.backgroundColor= '#FFC1C1'; rdiv.setAttribute("id", "msg"); var bodyRef = document.getElementsByTagName("body").item(0); bodyRef.appendChild(rdiv); var txt = document.createTextNode(vText); rdiv.appendChild (txt); } else{ var br = document.createElement("br"); eldiv.appendChild(br); var sp = document.createElement("span"); var txt = document.createTextNode(vText); sp.appendChild(txt); eldiv.appendChild(sp); } }
In the first line, we try to get the id of the div that will hold the messages.
If it is not on the page, we create it dynamically and append the text.
If the div tag is there, we add a break tag, a span tag and append the passed text.
Clear the text
To clear the text, use the following function:function clearText(){ var eldiv = document.getElementById('msg'); if(eldiv){ var bodyRef = document.getElementsByTagName("body").item(0); bodyRef.removeChild(eldiv); } }