documentFragment.querySelector Safari 问题
documentFragment.querySelector problem with Safari
我正在尝试使用 javascript querySelector
方法检索 documentFragment
中的元素。
我在 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/
我是不是遗漏了什么,还是只是一个错误?
在 Selectors Level 4 CSS 规范之前,要求匹配元素具有选择器的父元素,例如 nth-of-type
、first-child
等
这个新规范,仍然处于 工作草案 的状态,实现了这个新行为,现在元素不需要有父元素。
Safari 可能仍未实现新规范的这一部分,但当规范稳定后肯定会实现。
无论如何,这种行为仍应被视为实验性行为,您可能更喜欢使用其他方式来做同样的事情(例如,使用虚拟元素作为容器,直到将片段附加到文档中)。
我正在尝试使用 javascript querySelector
方法检索 documentFragment
中的元素。
我在 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/
我是不是遗漏了什么,还是只是一个错误?
在 Selectors Level 4 CSS 规范之前,要求匹配元素具有选择器的父元素,例如 nth-of-type
、first-child
等
这个新规范,仍然处于 工作草案 的状态,实现了这个新行为,现在元素不需要有父元素。
Safari 可能仍未实现新规范的这一部分,但当规范稳定后肯定会实现。
无论如何,这种行为仍应被视为实验性行为,您可能更喜欢使用其他方式来做同样的事情(例如,使用虚拟元素作为容器,直到将片段附加到文档中)。