Generating unexpected selector when specifying a root selector
abbadata opened this issue · 2 comments
Hi, for this test document, I am attempting to find a selector for <p>Line 1</p>
When no selector root is explicitly set, it returns:
#module > p
However, when I set the root selector to document.querySelector("#module")
, it still returns the same thing. I would think it should return a selector that doesn't contain #module since we are using that as the selector root?
test("root:setandfind", (t) => {
const html = `
<div class="document">
<div id="module">
<span id="span1"></span>
<p>Line 1</p>
<div id="introduction">
<h2>
Introduction
</h2>
<p>Line 2</p>
</div>
</div>
</div>
`;
document.write(html);
let rootelem = document.querySelector("#module");
let pElement = rootelem.querySelector("p");
const css = selector(pElement);
console.log("Default selector (no options): ", css);
const newcss2 = selector(pElement, { root: rootelem });
console.log("Selector after setting root to (#module): ", newcss2);
});
Output:
Default selector (no options): #module > p
Selector after setting root to (#module): #module > p
As you can see, the selector still seems to reference the ID of the root selector.
Is this a bug or am I misunderstanding the behavior of setting the root selector?
Hi, root
was designed to point to document like stuff, i.e. iframes and behavior in childNode are undefined. So it's a bug and not a bug at the same time.
Maybe it should not return it's root selector. What do you thing? Can you make a PR with such fix and tests?
On second thought, it may not make sense to not return the root selector. I think there are some documents where it really seems necessary. For example, even in this simple case, if #main is the root selector and we want to find a selector for <p>Line 1</p>
, it seems you'd have to use #main > p
. I don't think there's another clean, unique selector that doesn't include #main.. or at least I can't think of one.
<div id="main">
<p>Line 1</p>
<div>
<p>Line 2</p>
</div>
</div>