Narasimha Narasimha - 3 months ago 4x
Javascript Question

How to create a anchor link in javascript with dynamic arguments?

I am trying to create an anchor link when a user clicks on another link.

When I click on the first link, the onclick event is raised and generates another link using JavaScript, but that is not generated properly.

This is my anchor link in JavaScript:

temp="<li><a href='#' onclick='showMenu3('"+menu2[0]+"','"+menu2[2]+"')'>
<img src='images/noImageSmall.png'/>"+menu2[2]+"</a></li>";

But it is generated in the source as following:

<li><a href="#" onclick="showMenu3(" 139','invite="" a="" friend')'="">
<img src="images/noImageSmall.png">Invite a friend</a></li>

How can I generate the following link using JavaScript?

<li><a href="#" onclick="showMenu3('139','invite friend')">
<img src="images/noImageSmall.png">Invite a friend</a></li>


This will work:

var temp = '<li><a href="#" onclick="showMenu3(' + menu2[0] + ', \'' + menu2[2] + '\')"><img src="images/noImageSmall.png"/>' + menu2[2] + '</a></li>';

Not surprisingly, I agree with the others that this is not a good practice. It's error-prone, way too easy to generate invalid markup (which will introduce more bugs down the line) and you have to really understand string concatenation.

My preferred method is this:

var li = document.createElement('li'),
    a = document.createElement('a'),
    node = document.createTextNode(),
    img = document.createElement('img');
node.textContent = menu2[2];
img.src = "images/noImageSmall.png";
a.href = '#';
a.onclick = function(e) {
    var arg1 = menu2[0],
        arg2 = menu2[2];
    showMenu3(arg1, arg2);
    e = e || window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) {
    return false;

Here's a fiddle demonstrating both techniques:

Use a DOM inspector to see the markup generated.