0

I'm trying to add html elements to by index.html document using document.write(); The code that's giving me trouble is as follows:

... + "<td class='navbutton' onclick="location.href='./page1.html'">" + ...

The trouble is that the tag itself has to be inside quotes, and the onclick attribute within the tag contains quotes nested in quotes. I've tried using \ to include everything within the onclick element, but to no avail (I just get a console error saying,

Uncaught SyntaxError: missing ) after argument list

Can someone help me understand how to implement these triple nested quotes? Thank you

1 Answers1

4

Don't use inline handlers, they have horrible scoping rules and have problematic escaping issues like these, among other deficiencies. Instead of concatenating an inline listener an HTML string, consider attaching it properly with Javascript instead, it will be so much easier.

Insert the HTML:

<td class='navbutton'>

Then, select the td and add a listener to it. Eg, from the parent tr:

tr.querySelector('.navbutton').addEventListener('click', () => {
  window.location.href = './page1.html';
});

Or insert the <td> using appendChild (or appendAdjacentElement), eg:

const td = tr.appendChild(document.createElement('td'));
td.className = 'navbutton';
td.addEventListener('click', () => {
  window.location.href = './page1.html';
});
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320