Can use 2 crase signals (template strings
), which as described the documentation:
Template Strings are strings that allow embedded expressions. You can use multi-line string and string interpolation with them.
Basically it’s a new way to create strings and make your code a little more readable.
With its use, any structure can be inserted in elements in the DOM HTML, which will be interpreted as a single string, as you can see in the example:
$('body').append(`
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<th scope="row">3</th>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>
`);
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Vc tbm can use the oldest technique that would concatenate the elements, but, what can become unproductive and laborious depending on the amount of elements to concatenate:
$('body').append(
'<table class="table">'+
'<thead>'+
'<tr>'+
'<th scope="col">#</th>'+
'<th scope="col">First</th>'+
'<th scope="col">Last</th>'+
'<th scope="col">Handle</th>'+
'</tr>'+
'</thead>'+
'<tbody>'+
'<tr>'+
'<th>'+
'...'+
'</th>'+
'</tr>'+
'</tbody>'+
'</table>'
);
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
So tbm how can use own jQuery
to concatenate HTML elements, although this way I find much more limited by the fact that can not nesting elements:
$('body').append(
$('<div class="bg-danger"><p class="text-white">testes</p></div>'),
$('<ul><li>A</li></ul>'), $('<ul><li>B</li></ul>')
);
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Another way using jQuery itself would be with the method html(), as you can see in the example, the Bootstrap classes are not applied to the elements:
$('body').html(`
<div class="bg-danger"><p class="text-white">testes</p></div>
<ul><li>A</li></ul>
<ul><li>B</li></ul>
`);
.bg-danger {
background-color: red;
}
.text-white {
color: white;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
OBS: I didn’t understand why to give append in the body
with a modal structure
Thank you @Leandrade!
– Jaqueline Abreu
Ah, on the body I put to assign the modal to the body
– Jaqueline Abreu