Dynamically Adding Links (a href) using javascript and DOM

I’m adding this post strictly for the reason that every time I need to do this I spend about 20 minutes searching for an example, only to find various broken posts and incorrect answers. This way works for me every time. If you have an alternate way that works better or is less code, please feel free to post a comment.

var a = document.createElement('a');
a.setAttribute('href', 'page.html');
a.appendChild(document.createTextNode('Click Me'));

The interesting thing to note is that the text inside the link is not actually an attribute, rather it’s a a separate child node within the A element.

2 Responses to “Dynamically Adding Links (a href) using javascript and DOM”

  1. Ken Schultz June 18, 2010 at 4:56 pm #

    This would be the ‘only’ post I’ve ever made to one of these:

    Thank you! This actually works unlike most of the posts I’ve read.

  2. Sagar April 13, 2012 at 12:27 am #

    hello sir ..thanks for such nice blog..

    my javascript is looks like this

    this.searchfield = function(){

    // CONFIG

    // this is id of the search field you want to add this script to.
    // You can use your own id just make sure that it matches the search field in your html file.
    var id = “searchfield”;

    // Text you want to set as a default value of your search field.
    var defaultText = “Search the site…”;

    // set to either true or false
    // when set to true it will generate search suggestions list for search field based on content of variable below
    var suggestion = true;

    var suggestionText =”sagar,Moon”;

    var field = document.getElementById(id);
    var classInactive = “sf_inactive”;
    var classActive = “sf_active”;
    var classText = “sf_text”;
    var classSuggestion = “sf_suggestion”;
    this.safari = ((parseInt(navigator.productSub)>=20020000)&&(navigator.vendor.indexOf(“Apple Computer”)!=-1));
    if(field && !safari){
    field.value = defaultText;
    field.c = field.className;
    field.className = field.c + ” ” + classInactive;
    field.onfocus = function(){
    this.className = this.c + ” ” + classActive;
    this.value = (this.value == “” || this.value == defaultText) ? “” : this.value;
    };
    field.onblur = function(){
    this.className = (this.value != “” && this.value != defaultText) ? this.c + ” ” + classText : this.c + ” ” + classInactive;
    this.value = (this.value != “” && this.value != defaultText) ? this.value : defaultText;
    clearList();
    };
    if (suggestion){

    var selectedIndex = 0;

    field.setAttribute(“autocomplete”, “off”);
    var div = document.createElement(“div”);
    var list = document.createElement(“ul”);
    list.style.display = “none”;
    div.className = classSuggestion;
    list.style.width = field.offsetWidth + “px”;
    div.appendChild(list);
    field.parentNode.appendChild(div);

    field.onkeypress = function(e){

    var key = getKeyCode(e);

    if(key == 13){ // enter
    selectList();
    selectedIndex = 0;
    return false;
    };
    };

    field.onkeyup = function(e){

    var key = getKeyCode(e);

    switch(key){
    case 13:
    return false;
    break;
    case 27: // esc
    field.value = “”;
    selectedIndex = 0;
    clearList();
    break;
    case 38: // up
    navList(“up”);
    break;
    case 40: // down
    navList(“down”);
    break;
    default:
    startList();
    break;
    };
    };

    this.startList = function(){
    var arr = getListItems(field.value);
    if(field.value.length > 0){
    createList(arr);
    } else {
    clearList();
    };
    };

    this.getListItems = function(value){
    var arr = new Array();
    var src = suggestionText;
    var src = src.replace(/, /g, “,”);
    var arrSrc = src.split(“,”);
    for(i=0;i 0) {
    for(i=0;i<arr.length;i++){
    li = document.createElement("li");
    a = document.createElement("a");
    a.href = "javascript:void(0);";
    a.i = i+1;
    a.innerHTML = arr[i];
    li.i = i+1;
    li.onmouseover = function(){
    navListItem(this.i);
    };
    a.onmousedown = function(){
    selectedIndex = this.i;
    selectList(this.i);
    return false;
    };
    li.appendChild(a);
    list.setAttribute("tabindex", "-1");
    list.appendChild(li);
    };
    list.style.display = "block";
    } else {
    clearList();
    };
    };

    this.resetList = function(){
    var li = list.getElementsByTagName("li");
    var len = li.length;
    for(var i=0;i<len;i++){
    list.removeChild(li[0]);
    };
    };

    this.navList = function(dir){
    selectedIndex += (dir == "down") ? 1 : -1;
    li = list.getElementsByTagName("li");
    if (selectedIndex li.length) selectedIndex = 1;
    navListItem(selectedIndex);
    };

    this.navListItem = function(index){
    selectedIndex = index;
    li = list.getElementsByTagName(“li”);
    for(var i=0;i<li.length;i++){
    li[i].className = (i==(selectedIndex-1)) ? "selected" : "";
    };
    };

    this.selectList = function(){
    li = list.getElementsByTagName("li");
    a = li[selectedIndex-1].getElementsByTagName("a")[0];
    field.value = a.innerHTML;
    clearList();
    };

    };
    };

    this.clearList = function(){
    if(list){
    list.style.display = "none";
    selectedIndex = 0;
    };
    };
    this.getKeyCode = function(e){
    var code;
    if (!e) var e = window.event;
    if (e.keyCode) code = e.keyCode;
    return code;
    };

    };

    // script initiates on page load.

    this.addEvent = function(obj,type,fn){
    if(obj.attachEvent){
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn](window.event );}
    obj.attachEvent('on'+type, obj[type+fn]);
    } else {
    obj.addEventListener(type,fn,false);
    };
    };
    addEvent(window,"load",searchfield);

    ok sir ..

    an d i want to add href link in var suggestionText ="sagar,Moon";

    so when its click sagar it

    shows me index.html

    and if Moon its shows me index2.html

    so how can i Get this ..?? thanks in advance ..

Leave a Reply

Please leave these two fields as-is: