Wednesday, February 25, 2009

Dynamically adding an anchor tag with Javascript

I found a post with someone trying to add this:



<a name="Example" onmouseover="Tip('Example')" onmouseout="UnTip()">[?]</a>


to the page for each LI that has Element Search inside it.



As part of my own quest to get more familiar with Javascript I am going to take
this example on.




They need to be able to do this dynamically which means javascript on the client
side.



CODE


<li><a href="http://www.blogger.com/example.aspx">Example</a></li>




Requirments


The LI's are generated depending on user preferences, so we cannot just replace them.


We cannot alter the data pulled, only add functions after the data has loaded.







Here is what the poster had:



CODE



var items = gid('sideMenu').getElementsByTagName("li");

for(var i=0;i<items.length;i++){

    if(items[i].innerHTML == "Element Search"){

        var somehtml = document.write("<a name=\"Example\"
onmouseover=\"Tip('Example')\" onmouseout=\"UnTip()\">[?]</a>");

     
     items[i].appendChild(somehtml);

    }

}






This is a good start but Document.Write() does not really make an HTMLelement we
can grab.



Here is a different approch.  Lets use the createElement and createTextNode
functions that are on the document object.  In this way we are using the DOM
(Document Object Model) and not just writing to the document text.

CODE



for(var i=0;i<items.length;i++){

    if(items[i].innerHTML == "Element Search"){

        var anchorTag = document.createElement('a');

        anchorTag.appendChild(document.createTextNode("[?]"));



        anchorTag.setAttribuate('name', 'Example');

        anchorTag.setAttribute('onmouseover', 'Tip("Example")');

        anchorTag.setAttribute('onmouseout', 'UnTip()');

        items[i].appendChild(anchorTag);    

    }

}




If I get an example to test this I will but for now I am going to send it off to
that user.  Now we have created elements and dynamically added them using Javascript
to the DOM this should be a much more robust method.