1

I am trying to retrieve an element inside a documentFragment using javascript querySelector method.

I get what i expect with Chrome and Firefox, but not with 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/

Am I missing something, or is it just a bug?

Andreas
  • 21,535
  • 7
  • 47
  • 56
Simon Hi
  • 2,838
  • 1
  • 17
  • 17
  • So to make it clear, the discrepancy is only when using `:nth-xxx` pseudo selector on elements that are placed at the root of the frag. i.e, `querySelector("div")` (which does exactly the same as your selector btw) does work, same if you do append an element inside your `e` div and target it with `div>div:nth-of-type(1)` [(fiddle)](https://jsfiddle.net/9zj5b6cd/). I don't know the specs enough to determine if it is indeed a bug or not. – Kaiido Jan 01 '19 at 12:48
  • And actually, `div:nth-of-type(1)` will target the inner div in my fiddle (same as `div>div:nth-of-type(1)`): [(fiddle)](https://jsfiddle.net/z8bp13e4/) And if you wonder same for `first-child`and other pseudo-selectors, they're like disabled for elements at the root of the frag. – Kaiido Jan 01 '19 at 12:57
  • ... Fast reading [MDN article about `nth-of-type()`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-of-type#Specifications) it sounds like it is a recent addition that "*matching elements are not required to have a parent.*" (still a Draft). Safari probably didn't catch on yet. – Kaiido Jan 01 '19 at 13:03

1 Answers1

2

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.

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.

Anyway, this behavior should still be considered as experimental, and you might prefer use other ways to do the same thing (e.g use a dummy element as container until appending the fragment to the doc).

Kaiido
  • 123,334
  • 13
  • 219
  • 285