I want to load()
some external html that I have to embed in three(!) wrappers. This is the result I need:
<body>
<section class="page">
<div class="wrapper">
<div class="backdrop">
<!-- Loaded HTML -->
</div>
</div>
</section>
</body>
The following code works fine and looks clean, however, I want to add many <section>
, so it would be much nicer to somehow chain those append()
and the load()
:
$('body') .append('<section class="page"></section>');
$('section.page').append('<div class="wrapper"></div>');
$('div.wrapper') .append('<div class="backdrop"></div>');
$('div.backdrop').load ('partials/test.html');
I have found a few examples of chaining append()
, however, I failed to combine them with load()
.
Thanks in advance! :)
There's no need to use three separate append
calls, and as you point out, the way those are coded won't work if you add multiple sections.
Instead, create the full section fragment, append it to body, and then load into the backdrop:
$(
'<section class="page">' +
'<div class="wrapper">' +
'<div class="backdrop"></div>' +
'</div>' +
'</section>'
)
.appendTo('body')
.find('div.backdrop')
.load('partials/test.html');;
That's a bit cleaner if you separate the HTML from the code, e.g.:
var sectionTemplate =
'<section class="page">' +
'<div class="wrapper">' +
'<div class="backdrop"></div>' +
'</div>' +
'</section>';
then
$(sectionTemplate)
.appendTo('body')
.find('div.backdrop')
.load('partials/test.html');;