cheerio icon indicating copy to clipboard operation
cheerio copied to clipboard

Selector should not retrieve template content

Open andolf opened this issue 3 years ago • 3 comments

The MDN documentation for the <template> element specifies that its content is processed, but never rendered. This means that if you try to query the content you should end up with nothing. This behaviour was seemingly broken in rc4.

Simple code example:

const {load} = require("cheerio");

const $ = load(`<template id="temp">
  <div id="insert">
    <p>In a template</p>
  </div>
</template>
<div id="container"></div>`);

console.log("Inside template:", $("#insert").length); // 1, should be 0

const templateElement = $("#temp");
const templateContentClone = templateElement.contents();
$("#container").append(templateContentClone);

console.log("Now appended:", $("#insert").length); // outputs 1 as expected (but outputs 0 in rc3)

Whether this is a problem related to parse5 I don't know yet, the original implementation says that template contents cannot be queried directly but testing in a browser, you can query it as soon as it is added to the body and thus rendered.

andolf avatar Jul 13 '22 15:07 andolf

Parsing the content with parse5 seems to correctly parse the structure of the template element with no childNodes and the content property filled:

{
      nodeName: 'template',
      tagName: 'template',
      attrs: [Array],
      namespaceURI: 'http://www.w3.org/1999/xhtml',
      childNodes: [],
      parentNode: [Circular *1],
      content: [Object]
}

andolf avatar Jul 13 '22 15:07 andolf

Any progress with this issue?

paed01 avatar Oct 27 '22 12:10 paed01

No progress. This is an issue, and patches for css-select are welcome.

fb55 avatar Oct 31 '22 10:10 fb55