简体   繁体   English

Safari的documentFragment.querySelector问题

[英]documentFragment.querySelector problem with Safari

I am trying to retrieve an element inside a documentFragment using javascript querySelector method. 我正在尝试使用javascript querySelector方法检索documentFragment内的元素。

I get what i expect with Chrome and Firefox, but not with Safari (Mac OS, Safari 12.0.2). Chrome和Firefox可以达到我期望的效果,但Safari(Mac OS,Safari 12.0.2)却不能达到我的期望。

 function msg(s) { document.getElementById("a").innerHTML += s + "<br>"; } var myRoot, e; myRoot = document.createDocumentFragment(); e = document.createElement("div"); e.id = "child1"; e.innerHTML = "Hello!"; myRoot.appendChild(e); e = myRoot.querySelector("div:nth-of-type(1)"); if (e) { msg("1st div tag in fragment: " + e.id); } else { msg("Error when retrieving 1st div tag in fragment"); } document.body.appendChild(myRoot); e = document.querySelector("div:nth-of-type(1)"); if (e) { msg("1st div tag in document: " + e.id); } else { msg("Error when retrieving 1st div tag in document"); } 
 <p>Messages:</p> <p id="a"></p> <p>Inserted div:</p> 

jsFiddle: https://jsfiddle.net/bwqvrex2/ jsFiddle: https ://jsfiddle.net/bwqvrex2/

Am I missing something, or is it just a bug? 我是否缺少某些东西,还是只是一个错误?

Prior to Selectors Level 4 CSS specifications, it was required that the matching elements have a parent for selectors like nth-of-type , first-child etc. Selectors Level 4 CSS规范之前,要求匹配元素具有选择器的父级,例如nth-of-typefirst-child等。

This new specification, still in a state of Working Draft implements this new behavior, now elements don't need to have a parent. 仍处于工作草案状态的此新规范实现了此新行为,现在元素不需要父级。

Safari probably still didn't implemented this part of the new specs, but will certainly when the specs will have stabilised. Safari可能仍未实施新规范的这一部分,但是肯定会在规范稳定后才会实施。

Anyway, this behavior should still be considered as experimental, and you might prefer use other ways to do the same thing (eg use a dummy element as container until appending the fragment to the doc). 无论如何,这种行为仍应视为实验性的,并且您可能更喜欢使用其他方式来执行相同的操作(例如,使用虚拟元素作为容器,直到将片段追加到文档中为止)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM