Consider the following Javascript (which is probably not the best style):
var string = "There's an error here";
parent.innerHTML = '<div onclick="foo(\'+string+\')">'+string+'</div>';
Because of the single quote, the resulting HTML is not valid:
'<div onclick="foo('There's an error here')">There's an error here</div>'
One solution is to use the element's own innerHTML as the argument to foo() (since the function argument happens to be the same as the content of the element). However, this isn't a general solution.
Is it possible to deal with this issue using only an inline HTML solution? In my case, the inline HTML is much larger, and I can't easily convert it to a more 'proper' form, using DOM functions to create and append the HTML, and closures for the onclick functions.
I would say that your main issue is trying to attach event handlers using inline attributes instead of using addEventListener. All your issues will vanish if you respect good practices.
myDiv.addEventListener('click', function () {
foo("There's an error here");
});
However, if you still want to do it your way, you could simply escape the single quotes:
parent.innerHTML = '<div onclick="foo(\'' + string.replace(/'/g, "\\'") + '\');">' + string + '</div>';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With