Recently, I read the book "javascript Object-Oriented Programming Guide" again, read the browser environment chapter, and gradually understand that js, as a script language, must rely on the host environment to implement functions. From the browser perspective, is to operate the BOM and DOM of the browser. DOM operations can be divided into access, modification, deletion, and creation. Each operation has unique methods and attributes. The following example describes how to access, create, and delete a dom node (refer to the article ).
Function add () // example of dynamically adding a table {var parNode = document. getElementById ("Table1"); var tr = document. createElement ("tr"); var td = document. createElement ("td"); // create a td-type Element node td. appendChild (document. createTextNode ("This is the first column"); tr. appendChild (td); var td = document. createElement ("td"); // create a td-type Element node td. appendChild (document. createTextNode ("this is the second column"); tr. appendChild (td); parNode. appendChild (tr);} function remove () {var parNode = document. getElementById ("Table1"); var tr = document. getElementsByTagName ("tr"); alert (tr); // from this point, we can see that tr is a node table. Therefore, to delete a node, We need to specify which node needs to be deleted. removeChild (tr [0]);}
First, create two button elements in html and click the add and remove functions. GetElementById and getElementByTagName in the two functions are quick methods for dom element access. createElement and CreateTextNode are the methods for creating elements and text content respectively, removeChild also answers the comments in the reference article to remove sub-elements.