Using for loop and createElement() to Print out Array Content in JavaScript
Using for loop and createElement() to Print out Array Content in JavaScript. In this Article i will use a for loop to loop through all element contain inside an Array and then print out the Value line by line when the user click the ” check What is inside “ button .
Function in JavaScript that i will be using is as below:
- createElement(“div”)
- createTextNode(outputValues);
- createTextNode(outputValues);
- document.body.insertBefore(newDiv, currentDiv);
In Order to print out the element contains inside the Element line by line. The First thing i will need to do is to check how many element contains inside the Array. The Second thing is to Loop through all element contain inside the Array. While Looping through the Array i will need to create a new Div tag to insert the Array value text into the HTML Body.
Check out the code Using for Loop and createElement() to Print out Array Content in JavaScript
- To Print out the Element contain inside the Variable called ” newArray”. First i will need to check the array length inside the newArray variable.
- Then I create a variable called outputValues and then assign the element value in the newArray array into it, during every single looping process.
- Every time it loop through , it will create a new “div” tag by using the createElement() function
- Then i pass this newly created Div Tag into a new variable i called it newDiv
- Inside the new Div element i insert the content extract from newArrayassign to outputValues by using the createTextNode Function
- Then i get the id tag “divOut” by using the document.getElementById, and assign to a variable i called currentDiv
- document.body.insertBefore(newDiv, currentDiv); to insert the newly created div tag before the div tag with the ID divOut
function outArray() { var arraylen = newArray.length; for(var x=0; x<arraylen;x++){ newArray.toString(); var outputValues = newArray[x]; var newDiv = document.createElement("div"); //Create a new Div Tag with the createElement()Function var newContent = document.createTextNode(outputValues); // add the value inside the Array by using the createTextNode Function newDiv.appendChild(newContent); //Print out the newly created content var currentDiv = document.getElementById("divOut"); document.body.insertBefore(newDiv, currentDiv); } }
Check out how to remove and add an element into an Array using JavaScript here
Check out mdn JavaScript Library here
Leave a Reply