Monday, August 23, 2010

Create HTML element and import data by using javascript

After a long time i just struggled with this task and finally found a solution. As a HTML developer and a web designer i just enlarging my knowledge in Client side running scripts. So, I welcome your feedback and suggestion !


Creating a HTML element is bit easy but having data in a corresponding manner is some difficult. Yes, I have a series of data ummm ... For example i've an array with my details like Name, Age, Email ...etc., So, I need to pull that data to my HTML page in below format.



Fisrst Name : Arun


Last Name : raj


Age : 24


Email : arungetz@gmail.com


Address : Chennai



Got it right. Just have a look at below Javascript and HTML code.




function getdetails(){
var myarray = ['Arun','raj','24','arungetz@gmail.com','Chennai'];

var userdetails = document.getElementById('userdetails');
var inside = userdetails.getElementsByTagName('p');

for (i=0; i<inside.length; i++){
var insideP = inside[i].getElementsByTagName('span');

if(insideP.length == 0){
var myspan = document.createElement('<span>')
inside[i].appendChild(myspan);
myspan.innerHTML = myarray[i];
}
else {continue}
break;
}
}



<div id="userdetails">
<p>Fisrst Name : </p>
<p>Last Name : </p>
<p>Age : </p>
<p>Email : </p>
<p>Address : </p>
</div>
<input type="submit" onclick="getdetails()" value="Submit">



Initially we need to reach the <p> elements then going to add <span> element inside the <p> p tag. After that, the data need to be pulled here correspondingly. Finally having the correct data set.



var userdetails identifies 'userdetails' id. Then we're getting the paragraph tags by using getElementsByTagName, this has identified as inside. condition used whether the span tag there or not(insideP[i]). Initially there will be no span tag, so the span added.


myspan.innerHTML = myarray[i]; For every count of span added, the data from myarray will be pulled here(myarray[i]).break; is used to stop the action, when we click again the action will be continued.

No comments: