In actual use projects are often used to add js dynamic front-end code, such as dynamic add images and tables.
js html code to dynamically add two main methods:
1, appendChild () to implement nodes and add text content.
2, splice tag string, and add with innerHTML.
Specific examples:
1, appendChild () method:
//通过 createElement()方法来添加一个 p 元素 var p = document.createElement("p"); //通过 createTextNode()方法来添加一个文本节点 var node = document.createTextNode("我是一个新的段落,是js 的 appendChild 方法添加的!!"); //将文本节点添加到 p 元素中 p.appendChild(node); //获取所要添加的位置 var demo = document.getElementById("demo"); //在所需位置添加 p 元素 demo.appendChild(p);
2, splice tag string, and add with innerHTML. (Self believe this relatively simple method)
//通过 拼接 字符串 来添加 HTML 内容。 var name = '测试样例'; age = 18 ; var html = '' ; //动态添加一个段落 html += "<p> <b>我是另外一种方式添加的新段落!!!</b></p>"; //动态添加一个表格 html += '<table style="border:2px solid red;"> '; html += '<tr> <td> '+ name +' <td> </tr> '; html += '<tr> <td> '+ age +' <td> </tr> '; html += '</table>'; demo.innerHTML += html;
When string concatenation, middle name, age when populate values, can be replaced in accordance with the acquired value. Note stitching string format correctly.