Your current approach has a couple of problems -
function is a keyword. You cannot use it as a parameter.
- The way you are using it, you need function name here. Passing a callback won't help.
Rather than returning your anchor as a string, return it as an element -
function createAnchor(text, clickHandler) {
var link = document.createElement('a'); // creates an anchor element
link.href = "#"; // sets the href
link.onclick = clickHandler; // sets the click handler
link.innerHTML = text; // assigns the inner html string
return link; // now return it
}
and then -
var myAnchor = createAnchor('link', function () {
alert('test');
});
// Add this element wherever you want
See the documentation on createElement and element.
EDIT
If you want to add this anchor element to an existing DOM element as a child, use the appendChild -
var myAnchor = createAnchor('link', function () {
alert('test');
});
document.getElementById('x').appendChild(myAnchor);
Live JSFiddle.
EDIT 2
If you really want your anchor string, then create the anchor element using the above function, append it as a child to your desired element, and then use innerHTML on the parent. The approach is demonstrated here -
function createAnchorString(parentId, text, clickHandler) {
var link,
parent;
link = createAnchor(text, clickHandler); // call the previous function
parent = document.getElementById(parentId);
parent.appendChild(link);
return parent.innerHTML;
}
var myAnchorString = createAnchorString('x', 'link', function () {
alert('test');
});
alert(myAnchorString);
Live Fiddle.