rrrfusco
rrrfusco

Reputation: 1119

Convert text list of urls into clickable HTML links

I'm looking to convert a text list of urls into clickable links.

<!DOCTYPE html>

<body>  
<script>

// http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links
function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/

%=~_|])/ig;
    return text.replace(exp,"<a href='$1'>$1</a>"); 
}

var a1 = document.getElementById("test").innerHTML;
var a2 = replaceURLWithHTMLLinks(a1);
document.getElementById("test").innerHTML = a2;

</script>

<div id="test">
http://www.site.com/
http://www.site2.com/
http://www.site3.com/
</div>

</body>
</html>

Firebug returns the list of sites in the console for:

document.getElementById("test").innerHTML;

ie:
www.site.com/
www.site2.com/
www.site3.com/

Why do I get this error for the line below?

var a1 = document.getElementById("test").innerHTML;

TypeError: document.getElementById(...) is null

Upvotes: 3

Views: 2784

Answers (1)

PSL
PSL

Reputation: 123739

That is because you are trying to access the element before it has been added so document.getElementById('test') return null. You can wrap it under window.onload or add the script after the html element.

Try:

<script>

// http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links
function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/

%=~_|])/ig;
    return text.replace(exp,"<a href='$1'>$1</a>"); 
}

window.onload = function(){
  var elm =  document.getElementById("test");
  var modifiedHtml = replaceURLWithHTMLLinks(elm.innerHTML);
  elm.innerHTML = modifiedHtml ;
}

</script>

Upvotes: 4

Related Questions