Search code examples
javascriptselectors-apidocumentfragment

documentFragment.querySelector problem with Safari


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?


Solution

  • 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).