0

I have a problem with compiling in Visual Studio with JavaScript. In line 11, where there is datos.innerHTML,

alert("Hola Mundo");


var nombre = "Juan";
var altura = 180;
var concatenacion = nombre + " " + altura;
/*document.write(nombre);
document.write(altura);*/
/*document.write(concatenacion);*/
var datos = document.getElementById("datos");
datos.innerHTML = '

    <h1>Soy la caja de datos</h1>
    <h2>Mi nombres es: $(nombre)</h2>
    <h3>Altura: $(altura)</h3>
';

there is a problem with the compilation. Does not accept labels h1, h2, h3. Should I install an extension?

4 Answers 4

2

the other answer is correct, but you need to wrap with ${} for variable in order to used with ` (backticks)

  datos.innerHTML = `
        <h1>Soy la caja de datos</h1>
        <h2>Mi nombres es: (${nombre})</h2>
        <h3>Altura: (${altura})</h3>
    `;
Sign up to request clarification or add additional context in comments.

Comments

1

In Javascript, single/double quoted strings are always single line(without line continuations). To fix it, use a multiline string(aka template strings) by using backticks instead:

datos.innerHTML = `
    <h1>Soy la caja de datos</h1>
    <h2>Mi nombres es: $(nombre)</h2>
    <h3>Altura: $(altura)</h3>
`;

Edit: see Ari Firmanto's answer about using ${}.

Comments

0

The single quotes in that statement need to be backticks/grave marks ` rather than ':

datos.innerHTML = `

    <h1>Soy la caja de datos</h1>
    <h2>Mi nombres es: $(nombre)</h2>
    <h3>Altura: $(altura)</h3>
`;

Regular single and double quotes are for regular strings in JavaScript; template strings and multiline strings use the backtick character.

Comments

0

The error is because you have line breaks in the string.

Option 1

Keep the html string within quotes but concat the varialbles using + operator

datos.innerHTML = '<h1>Soy la caja de datos</h1><h2>Mi nombres es: ' 
                   + nombre + 
                   '</h2><h3>Altura: ' 
                   + altura + '</h3>';

Option 2

Use template literals and give variables like ${variable-name}. Check the support for Internet explorer if you are using this method.

datos.innerHTML = `
    <h1>Soy la caja de datos</h1>
    <h2>Mi nombres es: ${nombre}</h2>
    <h3>Altura: ${altura}</h3>
`;

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.