SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast mohammedsk's Avatar
    Join Date
    Nov 2005
    Location
    Columbia, Missouri
    Posts
    99
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Remove child nodes from parent node

    Hi,
    I am using the following code to remove child all nodes from a parent node.
    Code:
    function removeChildrenFromNode(node){
       var len = node.childNodes.length;
    	
    	for(var i = 0; i < len; i++)
    		node.removeChild(node.childNodes[i]);
    }
    The function removes all the child nodes except for the last one. The parent node is a "TD" element and the child nodes are three form elements (2 select inputs and one text input)

    Any ideas
    Thanks,

  2. #2
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Your loop should be for i <= len, or i < len+1.

    You could also do this using cloneNode:
    Code:
    function removeChildrenFromNode(node){
      var n = node.cloneNode(false), p = node.parentNode;
      p.insertBefore(n, node);
      p.removeChild(node);
    }

  3. #3
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    function removeChildrenFromNode(node){
         while(node.lastChild)node.removeChild(node.lastChild);
    }

  4. #4
    SitePoint Enthusiast mohammedsk's Avatar
    Join Date
    Nov 2005
    Location
    Columbia, Missouri
    Posts
    99
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you for your feedback. It was very helpful


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •