The example in this article describes how js uses DOM operations to implement a simple message board. Share it with everyone for your reference. The specific analysis is as follows:
The simple message board shown in the picture is a self-entertainment version. To put it bluntly, it is to practice DOM operations.
Point 1: document.createElement("tag name") creates a new element
Point 2: Parent element.appendChild("Element") Insert the new element into the tag of the page (displayed at the last tag), so that it will be displayed in the browser
Point 3: Parent element.insertBefore("Element","Before which element to insert") Insert the newly created element in front of the specified tag on the page, so that the content entered later will be displayed in the front
Point 4: Parent element.removeChild("Element") deletes the specified element
Below, the code:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>无标题文档</title> <script> window.onload = function(){ var oMsg = document.getElementById("msg"); var oBtn = document.getElementById("btn"); var oMsg_c = document.getElementById("msg_c"); var oUl = document.createElement("ul"); oMsg_c.appendChild(oUl); oBtn.onclick = function(){ var sVal = oMsg.value; var oli = document.createElement("li"); oli.innerHTML = sVal + " <span>删除</span>"; var oli1 = oUl.getElementsByTagName("li"); if(oli1.length>0){ oUl.insertBefore(oli,oli1[0]); }else{ oUl.appendChild(oli); } oMsg.value=''; var oSpan = document.getElementsByTagName("span"); for(var i=0; i<oSpan.length; i++){ oSpan[i].onclick = function(){ oUl.removeChild(this.parentNode); } } } } </script> </head> <body> <h1>简易留言板</h1> <input id="msg" type="text" size="40" value=""> <input id="btn" type="button" value="留言"> <div id="msg_c"></div> </body> </html>
I hope this article will be helpful to everyone’s JavaScript programming design.