-1

The project I'm working on uses double quotes for strings in HTML and JavaScript by default.
This has been decided and there is nothing I can do about it.
What hasn't been decided however, is how we should deal with nested quotations.

There are three options I can think of:

  1. Begin with outermost quote & alternate.
element.innerHTML = "<a href='...'></a>";
<button onclick="alert('...')"></button>
  1. Begin with innermost quote & alternate.
element.innerHTML = '<a href="..."></a>';
<button onclick='alert("...")'></button>
  1. Escape everything.
element.innerHTML = "<a href=\"...\"></a>";
<button onclick="alert(&quot;...&quot;)"></button>

Which is the best practice in terms of overall convenience, style, safety, maintainability, portability, etc.? And please suggest a better way if there is other than the above.

Affinity
  • 383
  • 1
  • 10
  • It's a bit ridiculous to require double quotes inside string literals. – evolutionxbox Feb 07 '20 at 10:58
  • 3
    None of those are a good idea, because escaping strings in HTML is tedious, and because [inline attribute handlers have terrible scoping rules](https://stackoverflow.com/a/59539045). Attach event listeners using Javascript instead – CertainPerformance Feb 07 '20 at 10:59

1 Answers1

0

I think the examples you gave are structured a little weird. Regardless, here's another option that I think you'll like better: template literals. You use backticks to define them. However, to use it effectively, you'll have to define your function outside of the string you passed into the HTML parameter for onclick.

Here's an example:

<button onclick="foo()">Click Me!</button>
<script>
  function foo() {
    alert(`"Hello"`);
  }
</script>
TrevLev
  • 109
  • 3
  • 11