SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Addict
    Join Date
    Sep 2004
    Location
    Denver
    Posts
    385
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Remove node without children nodes

    Is it possible to remove a DOM node in Javascript without removing its children nodes. say I have
    Code:
    <div id="ParentDiv">
      <div id="child1"></div>
      <div id="child1"></div>
    </div>
    Can i remove ParentDiv but still keep Child1,Child2 on the DOM tree? Thanks.

  2. #2
    SitePoint Wizard Pepejeria's Avatar
    Join Date
    Jan 2005
    Location
    Too far up north
    Posts
    1,566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I guess you need to iterate through the child nodes of the parentDiv and clone them to reinsert them after the parentDiv is gone

  3. #3
    SitePoint Addict
    Join Date
    Sep 2004
    Location
    Denver
    Posts
    385
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Pepejeria, I wanted to leave this solution as a last resort because I have a large number of child nodes and I'm not sure of the performance hit I'm taking here. Any thoughts?

  4. #4
    SitePoint Wizard Pepejeria's Avatar
    Join Date
    Jan 2005
    Location
    Too far up north
    Posts
    1,566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    What you also could do is to add yet another container div inside the parentDiv to hold all the child nodes, you would then only need to clone one div. The cloneNode method takes a boolean paremeter where you tell it to include the childNodes as well.

    And I guess you could simply use innerHTML as well instead of using the DOM that tends to be sloooooow in IE

  5. #5
    SitePoint Addict
    Join Date
    Sep 2004
    Location
    Denver
    Posts
    385
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Pepejeria, I like the cloneNode idea. Let me try it and see how it works. Thanks much for your help.

  6. #6
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,158
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Just move the child nodes up one level. No need for cloning.
    Code:
    var p = document.getElementById("ParentDiv");
    while (p.hasChildNodes()) {
        p.parentNode.insertBefore(p.firstChild, p);
    }
    p.parentNode.removeChild(p);
    Birnam wood is come to Dunsinane

  7. #7
    SitePoint Addict
    Join Date
    Sep 2004
    Location
    Denver
    Posts
    385
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Intersting thought. I didn't think about this one. Thanks AutisticCuckoo.


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
  •