Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Create Link Javascript

I'm trying to set my text as a link so that when I click on it, it runs a function. Right now I just have it set to google.com to try to get the text to appear as a link, but it doesn't seem to be doing anything at all. It's just static text. Any suggestions?

        var leftDiv = document.createElement("div"); //Create left div
        leftDiv.id = "left"; //Assign div id
        leftDiv.setAttribute("style", "float:left; width:66.5%; line-height: 26px; text-align:left; font-size:12pt; padding-left:8px; height:26px;"); //Set div attributes
        leftDiv.style.background =  divColor;
        a = document.createElement('a');
        a.setAttribute('href', 'google.com');
        user_name = a.appendChild(document.createTextNode(fullName + ' '));

        leftDiv.appendChild(user_name); // Add name to left div
like image 798
mkyong Avatar asked Mar 22 '12 21:03

mkyong


People also ask

Do HREF in JavaScript?

In JavaScript, you can call a function or snippet of JavaScript code through the HREF tag of a link. This can be useful because it means that the given JavaScript code is going to automatically run for someone clicking on the link. HREF refers to the “HREF” attribute within an A LINK tag (hyperlink in HTML).


1 Answers

Look at this example:

http://jsfiddle.net/ajXEW/

I added some comments inside the code that explain the diffrent steps.

    var leftDiv = document.createElement("div"); //Create left div
    leftDiv.id = "left"; //Assign div id
    leftDiv.setAttribute("style", "float:left; width:66.5%; line-height: 26px; text-align:left; font-size:12pt; padding-left:8px; height:26px;"); //Set div attributes
    leftDiv.style.background =  "#FF0000";
    a = document.createElement('a');
    a.href =  'google.com'; // Insted of calling setAttribute 
    a.innerHTML = "Link" // <a>INNER_TEXT</a>
    leftDiv.appendChild(a); // Append the link to the div
    document.body.appendChild(leftDiv); // And append the div to the document body
like image 151
Simon Edström Avatar answered Oct 07 '22 19:10

Simon Edström