Issue
The other day I's working on a project using jQuery 3.6.0 but I found that it can't parse <template> tags.
Refer to the below example.
const temp = $("#main");
console.log(temp.find("div").html()); // this isn't working
const temp2 = $("#main2");
console.log(temp2.find("div").html()); // this is working
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<template id="main">
<div class="first">
<span>Hola</span>
</div>
</template>
<div id="main2" style="display:none;">
<div class="first">
<span>Hola</span>
</div>
</div>
What am I doing wrong here?
Solution
template results in a document fragment in which the contents of the template element is. You have to access it using content.
So what you could do is $(temp[0].content).find('div').html()
But you need to be careful about that MDN: <template>: The Content Template element:
However, the HTMLTemplateElement has a
contentproperty, which is a read-only DocumentFragment containing the DOM subtree which the template represents. Note that directly using the value of the content could lead to unexpected behavior, see Avoiding DocumentFragment pitfall section below.
const temp = $("#main");
console.log($(temp[0].content).find('div').html()); // this isn't working
const temp2 = $("#main2");
console.log(temp2.find("div").html()); // this is working
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<template id="main">
<div class="first">
<span>Hola</span>
</div>
</template>
<div id="main2" style="display:none;">
<div class="first">
<span>Hola</span>
</div>
</div>
Answered By - t.niese
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.