[thelist] Simple JavaScript not working head scratcher

Howard Jess howard at dhitechnologies.com
Fri Mar 3 18:06:20 CST 2006


F wrote

> This should be simple, but for some reason I can't work out why this  
> isn't working.  This is what I've got:
> 
> <ul>
> <li>Quarter 1</li>
> <li>Quarter 2</li>
> </ul>
> 
> And this is what I want:
> 
> <ul>
> <li><a href="#">Quarter 1</a></li>
> <li><a href="#">Quarter 2</a></li>
> </ul>
> 
> Before anyone says anything, yes I know using JS to insert links is  
> bad 

Why is this bad? Unless your page *depends* on the links' existence,
there's nothing wrong with this.

> <script type="text/javascript">
> function alertnone()
>   {
>     var content = document.getElementById("content");
>     var lists = content.getElementsByTagName("ul");
>     var items = lists[0].getElementsByTagName("li");
>     for (var i=0;i<items.length;i++)
>      {
>         var a = document.createElement("a");
>         a.setAttribute("href", "#");
>         items[i].lastChild.insertBefore(a, items[i]);
>        }
>   }
> 
> window.onload = alertnone;
> 
> </script>
> 
> <ul>
> <li>Quarter 1 link</li>
> <li>Quarter 2 link</li>
> <li>Quarter 3 link</li>
>   </ul>

OK, look at this as a DOM tree:

    ul
        li
            [text]
        li
            [text]
        li
            [text]
            
In this line in your code            

    items[i].lastChild.insertBefore(a, items[i]);
        
  items[i] is an <li> element. 
  items[i].lastChild is a text node. 

So

  items[i].lastChild.insertBefore(a, items[i])

means
  
  insert the <a> element before the <li> (items[i]) child of the text
  node (items[i].lastChild). 
  
This is obviously wrong. You really want to move the text of the <li>
into the <a> you created, and make the <a> a child of the <li>; so
(untested):

function alertnone() {
    var content = document.getElementById("content");
    var lists = content.getElementsByTagName("ul");
    var items = lists[0].getElementsByTagName("li");
    for (var i=0;i<items.length;i++) {
        var a = document.createElement("a");
        a.href = '#';                           // simpler
        while (items[i].firstChild != null)     // Copies *all* children  
            a.appendChild(items[i].firstChild); // of the <li>
        items[i].appendChild(a);
    }
}


hj



More information about the thelist mailing list