Two Methods for dynamically creating elements in JS and two methods for dynamically creating elements in js
This article shares two methods for creating elements in js for your reference. The specific content is as follows:
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 is divided into three steps:
1. Create an element: Document. createElement ()
2. Find the parent element: You can use Id, name, tag 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 =" 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 is all the content of this article, hoping to help you learn.