One nice thing with jQuery is that the syntax (such as when chaining) allows your script to span multiple line breaks for ease of formatting and readability.
Is there an equivalent/preferred method when one is adding a large string of HTML?
For instance, it'd be nice to do something like this:
$("#theObject")
.doSomething()
.append("
<div>
<div>
Hello World
</div>
</div>
")
That doesn't work but is there something akin to that to make it easier to read HTML being formatted within a jQuery script?
There are three ways to create strings that span multiple lines: By using template literals. By using the + operator – the JavaScript concatenation operator. By using the \ operator – the JavaScript backslash operator and escape character.
There are three ways to create a multiline string in JavaScript. We can use the concatenation operator, a new line character (\n), and template literals. Template literals were introduced in ES6. They also let you add the contents of a variable into a string.
This is a long message that spans across multiple lines in the code. In the above example, the template literal ` ` is used to write multiline strings. The template literal was introduced in the newer version of JavaScript (ES6). Some browsers may not support the use of template literals.
You can have multiline strings in pure JavaScript. This method is based on the serialization of functions, which is defined to be implementation-dependent.
Add a \ at the end of each line
$("#theObject").doSomething()
.append("
<div>\
<div>\
Hello World\
</div>\
</div>\
")
Edit 2016:
If you're using ES6 (ES2015), you now can use template literals.
$("#theObject")
.doSomething()
.append(
"<div>"
+"<div>"
+"Hello World"
+"</div>"
+"</div>"
);
It'd be best practice to load your .append() content as a var, like so:
var append_me =
"<div>"
+"<div>"
+"Hello World"
+"</div>"
+"</div>";
$("#theObject").doSomething().append(append_me);
This can be done easier!
Use template literals: `
$("#theObject").doSomething()
.append(`
<div>
<div>
Hello World
</div>
</div>
`)
Documentation on template literals can be found here.
As @Geuis commented, this can only be used from es2015/ES6 (Can I use template literals).
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