2

I would like to add multiple lines of code to "myContent1" without having to replicate it as this can be quite tedious. Is there a more efficient way? Thanks!

function getCode(form){
    myContent1 = document.inputForm.myContent1.checked;
    output =
        '<!DOCTYPE html>\n' +
        '<html>\n' +
        '<body>\n' +
        ((myContent1) ? '<div>content 1</div>' : '') + '\n' +
        ((myContent1) ? '<div>content 2</div>' : '') + '\n' +
        '' +
        '<\/body>\n' +
        '<\/html>\n';
    document.inputForm.source.value = output;
    return output;
}
7
  • 2
    have you tried template literals? and I'm not sure why you're putting html and body into there Commented Jun 28, 2017 at 3:56
  • Are you talking about the repeated ternary expressions in the middle of your code? The easiest to read option would be to use an if block instead, but you could use a single ternary expression to concatenate several strings all at once: (myContent1 ? '<div>content 1</div><div>content 2</div>' + '<div>content 3</div>' + someVar + '<whatever>' : ''). Commented Jun 28, 2017 at 4:02
  • I do not understand your goal either. I will say HTML ignores newlines and most whitespace, so they are not necessary to build your page. That will save you some characters... Commented Jun 28, 2017 at 4:05
  • You got to try Template Literals. Commented Jun 28, 2017 at 4:06
  • @aduss apparently he is putting that generated HTML in a textarea or something, so he does need newlines and tabs to show as is. Commented Jun 28, 2017 at 4:07

1 Answer 1

2

You can use ES6 Template literals to achieve the same.

This is a sample code. I have modified the code to check the conditions too.

getCode()

function getConditionalTemplate(x, y) {

  if (Number(x) > Number(y)) {
    return `<div>content1</div>`
  } else {
    return `<div>content2</div>`
  }
}

function getCode() {
  const myContent1 = document.getElementById('inputForm');
  const x = 10000;
  const y = 200;

  const output =
    `<!DOCTYPE html>
        <html>
        <body> 
          ${getConditionalTemplate(`${x}`,`${y}`)}
        <\/body>
        <\/html>`
  myContent1.innerHTML = output;

}
<div id="inputForm">
</div>

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

1 Comment

You don't need the carriage return after the doctype

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.