I have a lot of elements that I need to display for mobile users, and plan to wrap all content within a template
, and then select the specific div
I would like and append it to the body
.
Why does the code below not append the div
to the body
as I would usually expect? I have used the most basic examples from other SO questions with no avail.
<template id="template">
<div id="page1">page1</div>
<div id="page2">page2</div>
</template>
And then jQuery:
function change_page(page_id){
var target = "#"+page_id;
var clone = $("#template").html();
$("body").append(clone.find(target));
}
$(clone).find('whatever');
So long as clone
contains html, and the whatever
is a valid selector for an element in that html, you can find elements that way. The key being you have to parse the html to dom elements first, which $(html)
does.
var template = $('#template').html(); $( document.body ).append( $(template).filter('#page2') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <template id="template"> <div id="page1">page1</div> <div id="page2">page2</div> </template>
However, given your template has two elements at the top level, you have to use filter()
instead of find()
in this case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.