Firstly, as others have mentioned, it should be userName
, not username
.
Secondly, don't use document.write. Use Element.innerHTML or create a textnode to append to the element, combined with editing the href
attribute.
The code becomes:
var userName = "cadler",
emServer = "mpl.gov",
emLink = userName + "@" + emServer;
document.getElementsByClassName("email")[0].innerHTML = "<a href='mailto:" + emLink + "'>"+emLink+"</a>";
<table border="1" cellpadding="5" cellspacing="0">
<tr>
<th>Name</th>
<th>Phone</th>
<th>E-Mail</th>
</tr>
<tr>
<td>Catherine Adler<br />Library Director</td>
<td>555-3100</td>
<td class="email"></td>
</tr>
</table>
var userName = "cadler",
emServer = "mpl.gov",
emLink = userName + "@" + emServer,
emTextNode = document.createTextNode(emLink),
elem = document.getElementsByClassName("email")[0];
elem.setAttribute("href", "mailto:" + emLink);
elem.appendChild(emTextNode);
<table border="1" cellpadding="5" cellspacing="0">
<tr>
<th>Name</th>
<th>Phone</th>
<th>E-Mail</th>
</tr>
<tr>
<td>Catherine Adler<br />Library Director</td>
<td>555-3100</td>
<td class="email"></td>
</tr>
</table>
As others mentioned, do not use document.write. That said, if you have to use document.write, then put the code inside the td
:
<td class="email">
<script>
var userName = "cadler",
emServer = "mpl.gov",
emLink = userName + "@" + emServer;
document.write("<a href='mailto:" + emLink + "'>");
document.write(emLink);
document.write("</a>");
</script>
</td>