1

Im using HTML inside .js file and it shows error when the HTML has new line like this

$(".message").click(function() {
    document.getElementById("timeline").innerHTML = ' <div>
    <p>Hello John</p>
    <ul>
        <li>Point A</li>
        <li>Point B</li>
        <li>Point C</li>
        <li>Point D</li>
    </ul>
</div>';
});

the above code will show error and will not work. but if i used the same code this way:

$(".message").click(function() {
document.getElementById("timeline").innerHTML = '<div><p>Hello John</p><ul><li>Point A</li><li>Point B</li><li>Point C</li><li>Point D</li></ul></div>';
});

is there any way to make the first code work in js file ?

thanks in advance.

John Dawn
  • 95
  • 1
  • 9

2 Answers2

1

Use this:

$(".message").click(function() {
document.getElementById("timeline").innerHTML = ` <div>
<p>Hello John</p>
<ul>
    <li>Point A</li>
    <li>Point B</li>
    <li>Point C</li>
    <li>Point D</li>
</ul>
</div>`;});

Please go ahead and lean about ES6. If you want to use '' then you have to concatenate.

Ryan
  • 396
  • 7
  • 23
Rob
  • 164
  • 1
  • 2
  • 12
0

You need to use backquote for multi-line text so that it is under the scope of same concatenation.

USING BACKQUOTE

$(".message").click(function() {
    document.getElementById("timeline").innerHTML = `<div>
    <p>Hello John</p>
    <ul>
        <li>Point A</li>
        <li>Point B</li>
        <li>Point C</li>
        <li>Point D</li>
    </ul>
</div>`;
});
$(".message").click(function() {
document.getElementById("timeline").innerHTML = '<div><p>Hello John</p><ul><li>Point A</li><li>Point B</li><li>Point C</li><li>Point D</li></ul></div>';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='timeline'></div>
<button class='message'>Click</button>

However, you can use + concatenation for each line like:

USING SEPARATE CONCATENATION

$(".message").click(function() {
    document.getElementById("timeline").innerHTML = '<div>'+
    '<p>Hello John</p>'+
    '<ul>'+
        '<li>Point A</li>'+
        '<li>Point B</li>'+
        '<li>Point C</li>'+
        '<li>Point D</li>'+
    '</ul>'+
'</div>'
});
$(".message").click(function() {
document.getElementById("timeline").innerHTML = '<div><p>Hello John</p><ul><li>Point A</li><li>Point B</li><li>Point C</li><li>Point D</li></ul></div>';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='timeline'></div>
<button class='message'>Click</button>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62