This article shares two methods of creating elements for your reference. The specific content is as follows
1) Splice the elements you need to create in the form of a string; find the parent element and directly assign the innerHTML of the parent element.
2) Use some functions provided by Document and Element objects to achieve dynamic creation of elements (create elements => Find parent elements => Insert elements at the specified position)
1. String splicing form
For a 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 div[id="container"], as shown in the figure below
<div id="container"> </div> <script> window.onload = function () { var str=''; for(var i=0; i<30 ;i++){ var r = parseInt(Math.random()*100); //Random generate a number str += '<div>'+r+'</div>'; //Split 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 in the figure below
Get the information in the input and insert it to the left or right of the red rectangle below according to the button on the right.
The solution is divided into three steps:
1. Create element: Document.createElement()
2. Find the parent element: you can match the specified css selector through Id, name, label name, class, and match the specified css selector
3. Insert elements at the specified position: element.appendChild(), element.insertBefore()
Implementation code:
<div id="div-input"> <input type="text" id="txt_input" value="4"/> <input type="button" id="leftInsert" value="leftInsert" /> <input type="button" id="rightInsert" value="rightInsert" /></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(){ //Input var span on the left side = document.createElement('span'); //1. Create element span.innerHTML=inputValue; var container = document.getElementById('container'); //2. Find the parent element container.insertBefore(span,container.childNodes[0]); //Insert to the leftmost} document.getElementById('rightInsert').onclick=function(){ //Input var span on the right side = document.createElement('span'); //1. Create element span.innerHTML=inputValue; var container = document.getElementById('container'); //2. Find the parent element container.appendChild(span); //3. Add element at the end} } </script>The above is all about this article, I hope it will be helpful to everyone's learning.