How to add Mailto: dynamically in Javascript

If this adds an email into a table, how do I get it to add it in the mailto: form?

Javascript:

var email = prompt("Please enter your Email");
        var personEmail = document.getElementById('personEmail');
        personEmail.innerHTML = email;

Html:

<table>
  <tr>
      <td>Email:</td>
       <td id="personEmail"> Email </a> </td>
  </tr>   
</table>

Thank you! (Very new to this)

1 answer

  • answered 2017-10-11 10:22 chsdk

    You need to use the given email value in the href attribute of your link:

    var email = prompt("Please enter your Email");
    var personEmail = document.getElementById('personEmail');
    personEmail.href = "mailto:" + email;
    personEmail.innerHTML = email;
    <table>
      <tr>
        <td>Email:</td>
        <td> <a id="personEmail">Email </a> </td>
      </tr>
    </table>

    Note:

    • Make sure to have a well structured HTML in the page you were using only a closing </a> in the table column.
    • I used the id="personEmail" with the <a> link instead of the td, if you need to use it in the td itself you need to change your JS.

    This is how it should be updated:

    var email = prompt("Please enter your Email");
    var personEmail = document.getElementById('personEmail');
    personEmail.querySelector("a").href = "mailto:" + email;
    personEmail.querySelector("a").innerHTML = email;
    

    Demo:

    var email = prompt("Please enter your Email");
    var personEmail = document.getElementById('personEmail');
    personEmail.querySelector("a").href = "mailto:" + email;
    personEmail.querySelector("a").innerHTML = email;
    <table>
      <tr>
        <td>Email:</td>
        <td id="personEmail"> <a>Email </a> </td>
      </tr>
    </table>