niklassc
niklassc

Reputation: 550

Need third kind of quotation marks in JavaScript

I'm changing the HTML using javascript. Therefore, I have a String that saves the HTML code, since it is produced in a for-loop. In it there is an <a> tag. To the <a> tag I want to add an onClick which calls a function with a parameter which is saved in a javascript variable.

let parameter = "p1";
let to_html_String = "<a href='#' onClick='create_sprite_window("+parameter+")'></a>";
document.getElementById('sidebar_left_sprites').innerHTML = to_html_String;

This does not work because it would prodece the following html:

<a href='#' onClick='create_sprite_window(p1)'></a>

It does not work because there are no quotation marks before and after p1. My problem is that I would need a third kind of quotation marks in order to solve this. In the following example I will use # where I would need those quotation marks:

let parameter = "p1";
let to_html_String = "<a href='#' onClick='create_sprite_window(#"+parameter+"#)'></a>";
document.getElementById('sidebar_left_sprites').innerHTML = to_html_String;

I can't use a single quotation mark because it would end the onClick and I can't use double beacuse it would end to_html_String.

Are there third quotation marks or is there an other way to solve this?

Upvotes: 2

Views: 2760

Answers (4)

Ry-
Ry-

Reputation: 225095

Don’t build HTML using JavaScript. The DOM API will let you build document nodes cleanly and safely, and even attach event listeners so you don’t have to build JavaScript strings in the HTML you’re building in JavaScript.

let parameter = "p1";

const link = document.createElement('a');
link.href = '#';
link.textContent = 'maybe you want something in this link?';
link.addEventListener('click', function (e) {
    e.preventDefault();
    create_sprite_window(parameter);
});

document.getElementById('sidebar_left_sprites')
    .appendChild(link);

Upvotes: 2

Prakash Bhavnath
Prakash Bhavnath

Reputation: 279

/* Use \' to differentiate with function single quote */

let parameter = "p1"; let to_html_String = ""; document.getElementById('sidebar_left_sprites').innerHTML = to_html_String;

Upvotes: 0

hsz
hsz

Reputation: 152266

If you're using ES6, you can use template strings like

let foo = `Hello "World's"`;

Anyway - why wouldn't you just escape your quotation marks ?

let bar = 'hello \' world';
let buz = "hello \" world";

Upvotes: 5

brk
brk

Reputation: 50326

This will work

"<a href='#' onClick='create_sprite_window('"+parameter+"')></a>";

Upvotes: 0

Related Questions