Home > Software design >  jQuery 3.6.0 can't parse "template" tag [duplicate]
jQuery 3.6.0 can't parse "template" tag [duplicate]

Time:09-22

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?

CodePudding user response:

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 content property, 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>

  • Related