Foreword:
There are two ways to create elements
1) Splice the elements that need to be created in the form of strings; find the parent element and directly assign a value to the innerHTML of the parent element.
2) Use some functions that come with Document and Element objects to dynamically create elements (create elements => find parent elements => insert elements at specified positions)
1. String concatenation form
For better understanding, set an application scenario.
Randomly generate a set of numbers, render this set of data into a bar chart, and place it in a div[id="container"], as shown below
<div id="container"> </div> <script> window.onload = function () { var str=''; for(var i=0; i<30 ;i++){ var r = parseInt(Math.random()*100); //随机生成一个数字 str += '<div>'+r+'</div>'; //拼接str } document.getElementById('container').innerHTML=str; } </script>
2. Use some functions that come with Document and Element objects
Also set an application scenario, as shown below
Get the information in the input and insert it to the left or right side of the red rectangle below according to the button on the right.
The solution is divided into three steps :
<div id="div-input"> <input type="text" id="txt_input" value="4"/> <input type="button" id="leftInsert" value="左侧入" /> <input type="button" id="rightInsert" value="右侧入" /> </div> <div id="container"> <span>1</span> <span>2</span> <span>3</span> </div> <script> window.onload = function () { var inputValue= document.getElementById('txt_input').value; document.getElementById('leftInsert').onclick=function(){ //左侧入 var span = document.createElement('span'); //1、创建元素 span.innerHTML=inputValue; var container = document.getElementById('container'); //2、找到父级元素 container.insertBefore(span,container.childNodes[0]);//插入到最左边 } document.getElementById('rightInsert').onclick=function(){ //右侧入 var span = document.createElement('span'); //1、创建元素 span.innerHTML=inputValue; var container = document.getElementById('container'); //2、找到父级元素 container.appendChild(span); //3、在末尾中添加元素 } } </script>