DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Hide Email Address From Spammers With Javascript

  • submit to reddit
function mangle() {
	if (!document.getElementsByTagName && !document.createElement &&
		!document.createTextNode) return;
	var nodes = document.getElementsByTagName("span");
	for(var i=nodes.length-1;i>=0;i--) {
		if (nodes[i].className=="change") {
			var at = / at /;
			var dot = / dot /g;
			var node = document.createElement("a");
			var address = nodes[i].firstChild.nodeValue;

			address = address.replace(at, "@");
			address = address.replace(dot, ".");

			address = address.replace(at, "@");
			address = address.replace(dot, ".");
			node.setAttribute("href", "mailto:"+address);
			var prnt = nodes[i].parentNode;
			for(var j=0;j<prnt.childNodes.length;j++)
				if (prnt.childNodes[j] == nodes[i]) {
					if (!prnt.replaceChild) return;
					prnt.replaceChild(node, prnt.childNodes[j]);

You can use this script, if you'd like to post your email address to your homepage, but don't want to see it picked up by spammers.

Just run it in your onload event handler and mark emails in your HTML as:

      <span class="change">markos at gaivo dot net</span>

This way they are still recognizable by those who don't use javascript.

If you need help or want to discuss this code, please do it on my <a href="">blog</a>.