SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Zealot
    Join Date
    Jul 2005
    Location
    Osoyoos BC Canada
    Posts
    178
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    insertBefore I can't make it work!

    I have a site where I use appendChild to insert unique links at the end of each block which are marked up using divs of <div id="sect_1" class="section">..</div> id="sect_2" class="section">..</div> etc.

    I iterate through the class="section", explode the id on the _ and get a unique identifier sect[i] for each section and use
    Code:
    sect[i].appendChild(newLink)
    to insert a unique link, (which is composed in part of the sect[1] that I parsed out, and is stored in newLink).

    This works, but it appears at the end of the div.

    Ideally I'd like it to appear before the text in the div appears.

    I have tried various permutations of
    Code:
    insertBefore(newLink,document.sect[i].firstChild)
    But although firefox reports no javascript errors, nothing shows up in the page.

    I've had a good hunt on the web to try and see what I'm doing wrong, but can't see where I'm obviously missing something!

    Any advice would be appreciated!

    (BTW. Sounds silly, but if there is an 'appendChild' why isn't there a 'prependChild'?)

    Thanks!

  2. #2
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    insertBefore has to be called for the immediate parent of the element in the second parameter.
    Is that what you're doing and can you show a working example?
    Tab-indentation is a crime against humanity.

  3. #3
    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)
    The usual way to add an element to the start of a container is with the following.

    Code javascript:
    if (refEl.firstChild) {
        refEl.insertBefore(el, refEl.firstChild);
    } else {
        refEl.appendChild(el);
    }

    The check for a firstchild is useful in cases where an element has no children.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


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
  •