tab is not displaying propely

tab is not displaying propely

Im creating a dynamic tab, shown below is the code.

  1. function addTab(tabCounter, tabName)
  2. {
  3. var i = tabCounter;
  4. var tabTitle = tabName;
  5. var a_el=document.createElement('a');
  6. a_el.setAttribute("href", "#tabs-" + i);
  7. a_el.appendChild(document.createTextNode(tabTitle));
  8. var li_el = document.createElement('li');
  9. li_el.appendChild(a_el);
  10. document.getElementById("ul_id").appendChild(li_el);
  11. var par = document.createElement('p');
  12. par.appendChild(document.createTextNode("content for added node " + i));
  13. //add tab 
  14. var dib = document.createElement('div');
  15. dib.setAttribute("id","tabs-"+i);
  16. dib.appendChild(par);
  17. var test=document.getElementById("tabs")
  18. test.appendChild(dib);
  19. }
  20. function provideData()
  21. {
  22.       for(var i=1; i<5; i++){
  23.       addTab("data" +i , "anotherdata"+i);
  24.       }
  25. }
However I get weird result, the tab title is not divided and the tab contents are displayed all at once.
The output is shown below.
    
But when I put the entire code for adding tab inside a for loop to test if it functions properly, the code is working flawlessy.

  1. function addTab()
  2. {
  3.       for(x=1; x<4; x++)
  4.       {
  5.             [code to create tab]
  6.             .....
  7.             .....
  8.       }
  9. }

WHat do I need to do to make the code in the upper part of the page work perfectly? And what's the difference between these the two that results to a different output?