Question

I have an html that looks like this

<div id="tabs"> 

  <ul id="ul_id"> 
    <li><a href="#tabs-1">tab 1</a></li> 
    <li><a href="#tabs-2">tab 2</a></li> 
    <li><a href="#tabs-3">tab 3</a></li> 
  </ul> 

  <div id="tabs-1"> <p>tab 1 contents</p> </div> 
  <div id="tabs-2"> <p>tab 2 contents</p> </div> 
  <div id="tabs-3"> <p>tab 3 contents</p> </div>

</div>

What I need to do is make this code dynamic because the number of tabs is not fixed.

What I have done so far is this

<script>
  par = document.createElement('p')
  par.setAttribute("text","Adding nodes");
  dib = document.createElement('div')
  dib.setAttribute("id","tabs-4");
  dib.appendChild(par);
  test=document.getElementById("tabs")
  test.appendChild(dib);
  for(i=0; i< test.childNodes.length; i++)
  {
    document.getElementsByName
    if(test.childNodes[i].getAttribute("id") == "ul_id")
      alert("equal");
    else
      alert(test.childNodes[i].getAttribute("id"));
  }
</script>

Create an element for <p>

Create an element for div

Append(appendChild) the div element to tabs

Now Im stuck with the part of getting the tag name and id name of the child nodes of tag.. I need to add the new entry to the list.

How will I do that?

i thought of using getElementsByName but that would mean that I need to add a name attribute to the ul. Im not sure if that was a good idea so I Im thinking of other possible ways to do it. Please help. thanks

Was it helpful?

Solution

Adding a tab looks like it should be something done as a function rather than inline, so you could write it like this

                                 // i is the last id
var addTab = (function (tab_root, nav_root, i) { // IIFE to create closure
    return function (title, contents) {
        var li, a, div, j;
        // get id
        j = ++i; // I put it in it's own var to avoid race conditions
        // create nav
        li = document.createElement('li');
        a = document.createElement('a');
        a.setAttribute('href', '#tabs-' + j);
        if (title) a.appendChild(document.createTextNode(title));
        li.appendChild(a);
        // create tab
        div =  document.createElement('div');
        if (contents) div.appendChild(document.createTextNode(contents));
        // append to document
        tab_root.appendChild(div);
        nav_root.appendChild(li);
        return {tab: div, nav: a, id: j};
    }
}(document.getElementById('tabs'), document.getElementById('ul_id'), 3)());
// invoke IIFE with initials i.e. id 3 for 3 tabs existing

now

addTab('tab 4', 'tab 4 contents');

An Object is returned with properties tab, nav and id. This lets you do more work with the different parts as required.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top