SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Evangelist NokX's Avatar
    Join Date
    Feb 2003
    Location
    Knoxville, TN
    Posts
    525
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    appendChild to the top of a list

    i'm wanting to add a new <li> to an existing <ul>, but i want it to appear at the top of the list - not append to the bottom.

    i'm assuming there's a semi easy way to do this?

    Code:
    var ul = document.getElementById('my-list');
    var li = document.createElement('li');
    ul.appendChild(li);
    that's currently how appending works, i just want to add it at the top.

  2. #2
    SitePoint Wizard gRoberts's Avatar
    Join Date
    Oct 2004
    Location
    Birtley, UK
    Posts
    2,439
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    use insertBefore ie

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <title>Untitled Document</title>
            <link rel="stylesheet" type="text/css" media="screen" />
            <style type="text/css"></style>
            <script type="text/javascript">
                function add(what, where) {
                    var d = document.getElementById('test');
                    var li = document.createElement('LI');
                        li.appendChild(document.createTextNode(what));
                    d.insertBefore(li, d.childNodes[where]);
                }
            </script>
        </head>
        <body>
            
            <ul id="test">
                <li>1</li>
                <li>2</li>
                <li>3</li>
                <li>4</li>
                <li>5</li>
                <li>6</li>
                <li>7</li>
                <li>8</li>
                <li>9</li>
            </ul>
    
            <br /><a href="javascript:add('10',0);">Add 10 at 0</a>
    
        </body>
    </html>



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
  •