0

Hello I am trying to store some html output in a JS var to output it to the page using "getElementById"...

The problem I am having is with single quotes versus double quotes and when to wrap them within each other...

here is my code:

var buttonOutput1="<br/>";
var buttonOutput2="<button onclick="DealCard('player')">Hit</button>";
var buttonOutput5=buttonOutput1+buttonOutput2;

document.getElementById('buttonArea').innerHTML = buttonOutput5;

I know a little about this, I know you can enclose something within single quotes and then enclose that within double quotes and it all works fine.

But because I want to store it all in a variable, I need to enclose it all in a third set of quotes and so therein is my problem.

So just stuck on what I should do here, wondering if anyone can help on this.

Thanks, G

**** My solution 12:51PM EST ****

Was able figure this out by breaking it into pieces:

var buttonOutput1="<br/>";
var buttonOutput2a="DealCard('player')";
var buttonOutput2b='<button onclick="' + buttonOutput2a + '">Hit 
Me</button>';
var buttonOutput5=buttonOutput1+buttonOutput2b;





document.getElementById('buttonArea').innerHTML = buttonOutput5;
2
  • 1
    If your target browsers support ECMAScript 6(caniuse.com/#feat=template-literals), you can use ` ` backticks(developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…), that will allow you to mix double and single quotes with no need to escaping. Commented Jul 15, 2017 at 16:46
  • Thanks so much yuriy - I figured it out a different way right after writing this, but I will be looking at your input - the way i got it to work was splitting it into pieces and multiple steps - I am sure your way is better so I will be looking at it. I will update my question with my new code... Commented Jul 15, 2017 at 16:51

1 Answer 1

2

You can create a DOM node using create Element (DOM Level 2) and attach a function to the onclick attribute.

var domNode = document.createElement('button');
domNode.innerHTML = 'Click me';
domNode.onclick = function() {
  alert("hello world")
};

document.getElementById('hook').appendChild(domNode);
<div id="hook"></div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.