Lucifer N.
Lucifer N.

Reputation: 1056

How to convert a string to a hyperlink with Javascript?

So I am working with some data that gets sent back from the server after a file upload in Javascript. It is sending back a URL, and I need it to appear as a hyperlink and append it to the document. What is the best way to go about doing this? I could do it serverside though that doesn't seem to be very clean, and I googled and found the str.link() method but read it was deprecated. My code in JS:

init: function() {
    this.on("success", function(file, responseText) {
        var span = document.createElement('span'); 
        span.setAttribute("style", "position: absolute; bottom: -28px; left: 3px; height: 28px; line-height: 28px;   "); 
        span.innerHTML = responseText;
        file.previewTemplate.appendChild(span);

    });
}

Upvotes: 1

Views: 1158

Answers (2)

Cerbrus
Cerbrus

Reputation: 72839

Try this:

var a = document.createElement('a'); // Create a new <a>
a.href = responseText;              // Set it's href
a.innerHTML = responseText;        // Set it's text
span.appendChild(a);              // Append it to the span

(Or you can just replace the span with the <a> altogether.)
In that case, you'll obviously have to apply the css to the <a>:

a.setAttribute("style", "position: absolute; bottom: -28px; left: 3px; height: 28px; line-height: 28px;");

However, using a css class would be cleaner:

a.className = "MyCssClass";

Upvotes: 2

Samuel Caillerie
Samuel Caillerie

Reputation: 8275

You can create an hyperlink instead of a span :

var link = document.createElement('a');
link.href = responseText;
link.innerHTML = responseText;

Upvotes: 2

Related Questions