SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Sep 2010
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How to dynamically add anchor tag using javascript ?

    Hi,

    I need to add acnhor tag dynamically using javascript. I have achived this using following code, but there is little prioblem.

    Code:
     function addURL(token){
      	   var tableObject = document.getElementById("tableConfirmationsToAttach");
    	   var rowCount = tableObject.rows.length;
    	   
    	   var row = tableObject.insertRow(rowCount);  	
    
    	  var cell2 = row.insertCell(0);
    	
    	  
    	   cell1 = document.createElement("<td class='footnote'>");
    	        
    	
    	  //cell1.innerHTML = "<a href='"javascript:launchANewWindow(" + "'" + token + "' " + ", "  + "'" + "document" + "')" + "' >"+ token +"</a>";
    	  	  
    	  cell1.innerHTML = "<a href='"+ token +"' >"+ token +"</a>";
    	   
    	  cell2.appendChild(cell1);                             
     
     }
    if I use a codeline like
    Code:
      cell1.innerHTML = "<a href='"+ token +"' >"+ token +"</a>";
    Evrything works fine, but I need to set a fucntion call (having 2 paramters)
    in href, something like below
    Code:
     cell1.innerHTML = "<a href='"javascript:launchANewWindow(" + "'" + token + "' " + ", "  + "'" + "document" + "')" + "' >"+ token +"</a>";

    but this doesn't work

    Can anybody here, help me with this ?

    thanks in Advance.

  2. #2
    SitePoint Evangelist TommiChi's Avatar
    Join Date
    Oct 2008
    Posts
    440
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You chose to go the innerHTML way (rather than createElement and appendChild/insertBefore), which is an option, but putting javascript syntax in the HREF is really bad practice....

    What you want to do is give your anchor an id, then use addEventListener/attachEvent to attach a function to your click event. For example:
    cell1.innerHTML = '<a id="myAnchor">'+ token +'</a>';
    if(typeof document.addEventListener != 'undefined') {
    document.getElementById('myAnchor').addEventListener('click', function() {
    myFunction(params);
    }, false);
    }
    else {
    document.getElementById('myAnchor').attachEvent('onclick', function() {
    myFunction(params);
    });
    }


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
  •