3

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

rrrfusco
  • 1,099
  • 5
  • 19
  • 46
  • Why do you want to do this? If you're trying to scrub URLs you might consider using PHP's DOMDocument, instead of JavaScript. Personally, I rarely see links on a page, that are not actual links. – StackSlave Dec 06 '13 at 01:14

1 Answers1

4

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>
PSL
  • 123,204
  • 21
  • 253
  • 243