Analysis of JS dynamic creation elements [two methods], analysis of js dynamic two methods
Preface:
There are two ways to create an element
1) concatenate the elements to be created into strings. Locate the parent element and assign values to the innnerHTML of the parent element.
2) use some functions provided by Document and Element objects to dynamically create elements (create Element => Find parent Element => insert Element at specified position)
I. String concatenation
Set an Application Scenario for better understanding.
Randomly generate a group of numbers and render the group of data as a bar chart, which is placed in div [id = "container"], as shown in
<Div id = "container"> </div> <script> window. onload = function () {var str = ''; for (var I = 0; I <30; I ++) {var r = parseInt (Math. random () * 100); // generates a random number str + = '<div>' + r + '</div>'; // concatenates str} document. getElementById ('Container '). innerHTML = str ;}</script>
Ii. Use some functions provided by Document and Element objects
Also set an application scenario, such
Obtain the information in the input, and insert the information to the left or right of the red rectangle to the bottom according to the buttons on the right.
The solution consists of three steps::
- Create element: Document. createElement ()
- Find the parent element: You can use Id, name, tag name, class, and match the specified css selector.
- 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 =" left-side "/> <input type =" button "id =" rightInsert "value =" right-side "/> </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 = document on the left. createElement ('span '); // 1. Create an element span. innerHTML = inputValue; var container = document. getElementById ('Container'); // 2. Locate the parent element container. insertBefore (span, container. childNodes [0]); // insert to leftmost} document. getElementById ('rightinsert '). onclick = function () {// input var span = document to the right. createElement ('span '); // 1. Create an element span. innerHTML = inputValue; var container = document. getElementById ('Container'); // 2. Locate the parent element container. appendChild (span); // 3. Add an element to the end }}</script>
The above analysis of the JS dynamic creation element [two methods] is all the content shared by the editor. I hope to give you a reference, and I hope you can also support the help house.