My html code has "a" tag inside "td" tag like below code.
<td align="left"> <a href="besir.html" target="_blank"> KASSAB Besir </a> </td>
I want to add new clickable line to my table with javascript. My js code is given below.
const createTD = document.createElement('td');
const createTDA = document.createElement('a');
createTD.align = "left";
createTD.innerHTML = "SURNAME Name";
createTDA.setAttribute('href', 'https://www.exampleurl.com');
createTD.appendChild(createTDA);
A new row is added to the table but the above code is not working properly. td is created but not clickable.
You are appending an empty <a> tag since you are not using innerHTML for it
createTD.innerHTML = "SURNAME Name"; // Incorrect
createTDA.innerHTML = "SURNAME Name"; // Correct
const createTD = document.createElement('td');
const createTDA = document.createElement('a');
createTD.align = "left";
createTDA.innerHTML = "SURNAME Name";
createTDA.setAttribute('href', 'https://www.exampleurl.com');
createTD.appendChild(createTDA);
document.body.append(createTD);
Your code is almost working; the mistake you made was setting the text in the innerHTML of the table cell, instead of the anchor tag -- so the link existed, it was just invisible because there was nothing inside it.
Here's a corrected version (with some extra code to demonstrate its usage, since you omitted the part that actually attaches anything to the DOM)
function AddTD() {
const createTD = document.createElement('td');
const createTDA = document.createElement('a');
createTD.align = "left";
createTDA.innerHTML = "SURNAME Name"; // <-- changed this
createTDA.setAttribute('href', 'https://www.example.com');
createTD.appendChild(createTDA);
// added code to append the new cell to the table:
document.getElementsByTagName('tr')[0].appendChild(createTD)
}
<table>
<tr></tr>
</table>
<button onclick="AddTD()">Add</button>
It's maybe worth noting that you can do this more easily and readably by inserting the full html string instead of using individual DOM methods:
function AddTD() {
const createTD = `<td align="left"><a href="//example.com">SURNAME name</a></td>`;
document.getElementsByTagName('tr')[0].innerHTML += createTD
}
<table>
<tr></tr>
</table>
<button onclick="AddTD()">Add</button>
You can try:
function createAnchorTag() {
// Create anchor element.
let a = document.createElement('a');
// Create the text node for anchor element.
let link = document.createTextNode("This is link");
// Append the text node to anchor element.
a.appendChild(link);
// Set the title.
a.title = "This is Link";
// Set the href property.
a.href = "https://example.org";
// Return newly anchor tag
return a;
}