SitePoint Sponsor

User Tag List

Results 1 to 6 of 6

Thread: Parent Node

  1. #1
    SitePoint Member
    Join Date
    Jul 2006
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Parent Node

    Whats the easiest way to change a given elements parent?

  2. #2
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Nelson BC
    Posts
    2,310
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    newParent.appendChild(element);

  3. #3
    SitePoint Member
    Join Date
    Jul 2006
    Posts
    8
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Will that work if element already has a parent?

  4. #4
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Yes it will. Counterintuitive though it may be, appendChild moves an existing element
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  5. #5
    SitePoint Zealot
    Join Date
    Feb 2006
    Posts
    184
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Nodes can only have one parent. This is why when you move elements around in a document, they are not duplicated, but rather removed from their previous position and put into a new position. So appending an element to another will in fact change its position in the DOM tree and give it a new parent node.

  6. #6
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Nelson BC
    Posts
    2,310
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You can copy a node and all its children to a new parent like this:
    newParent.appendChild(element.cloneNode(true));

    That won't touch the original


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
  •