0

i have to add multiple thumbnail images(501.jpg,502.jpg etc. added in the gengrid function) in a page each of which opens another image(port.jpg) on click and on clicking another thumbnail image the port.jpg has to be removed. The problem is that the removeChild is not working in this case. Can anyone please help... here is the code

<script type="text/javascript">
var lastper=null;
function gengrid()
      {
          var i=0;
          var num_stud=8;
          var newdiv;
          var divIdName;
          var maindiv;
          for(i=1;i<=num_stud;i++)
          {
             newdiv = document.createElement('div');
             divIdName = '50'+i;
             newdiv.setAttribute('id',divIdName);
             newdiv.setAttribute('onclick','addit('+i+')');
             newdiv.innerHTML = '<img src=50'+i+'.jpg alt="a"></img>';
             maindiv=document.getElementById('main');
             maindiv.appendChild(newdiv);
          }
      }
   gengrid();
   function addit(picno)
      {
          var person = document.getElementById('50'+picno);
          if(lastper)
             lastper.removeChild('portfolio');
          var newdiv = document.createElement('div');
          var divIdName = 'portfolio';
          newdiv.setAttribute('id',divIdName);
          newdiv.innerHTML ='<img src="port.jpg" alt="a"></img>';
          person.appendChild(newdiv);
          alert(picno+''+lastper.id+person.id);
          lastper = document.getElementById('50'+picno);
       } 
  </script>

4 Answers4

0
if(lastper){
         lastper.removeChild('portfolio');return;}
Ragavan
  • 997
  • 7
  • 11
0

I don't believe this is a valid ID for an element. An ID must begin with a letter.

lastper = document.getElementById('50'+picno);

What are valid values for the id attribute in HTML?

Community
  • 1
  • 1
Marc Costello
  • 439
  • 1
  • 3
  • 12
0

Try this

  function addit(picno)
  {
      var person = document.getElementById('50'+picno);
      lastper = document.getElementById('50'+picno);
      if(lastper)
         lastper.removeChild('portfolio');
      var newdiv = document.createElement('div');
      var divIdName = 'portfolio';
      newdiv.setAttribute('id',divIdName);
      newdiv.innerHTML ='<img src="port.jpg" alt="a"></img>';
      person.appendChild(newdiv);
      alert(picno+''+lastper.id+person.id);          
   } 
Shafeeque
  • 2,039
  • 2
  • 13
  • 28
0

The main issue is that you're passing a string to the removeChild call. Using

lastper.removeChild(document.getElementById('portfolio'));

instead will fix that problem.

The alert you have is a secondary issue. It'll fail the first time through because "lastper" is null and so doesn't have an id property.

Benjamin Warren
  • 529
  • 4
  • 5