Matthew Spahr
Matthew Spahr

Reputation: 237

How to nest an anchor element within a table cell?

I am looking to create this using javascript but am not getting it correct:

<td>
    <a href="https://google.com">
        Google
    </a>
</td>

My current JS looks like this:

var value = "Google";
var draftLink = document.createElement("a");

draftLink.href = "https://google.com";
draftLink.innerHTML = value;

td.innerHTML = draftLink;

I am ending up with

<td>
    https://google.com
<td>

Upvotes: 0

Views: 162

Answers (1)

j08691
j08691

Reputation: 207943

Assuming that your td variable gets the table cell that you want, use appendChild instead:

var value = "Google";
var draftLink = document.createElement("a");
draftLink.href = "https://google.com";
draftLink.innerHTML = value;

td.appendChild(draftLink);

var value = "Google";
var draftLink = document.createElement("a");
var td = document.getElementsByTagName('td')[0];
draftLink.href = "https://google.com";
draftLink.innerHTML = value;

td.appendChild(draftLink);
<table>
  <tr>
    <td>

    </td>
  </tr>
</table>

Upvotes: 1

Related Questions