Developing a compact querying module (using js) for html is my current project, and I aim to create a versatile query(selector)
function that can handle both css selectors and XPath selectors in string form.
My dilemma lies in determining whether a given string represents an xpath or a css selector. If we imagine the function layout:
function query(selector){
selectorKind = identifySelectorKind(selector); // The mystery lies here
if(selectorKind==="css") return queryCss(selector);
if(selectorKind==="xPath") return queryXPath(selector); //Both functions exist and are functional
}
Given my limited understanding of xPath queries, I initially considered identifying the type by checking if the first character is /
since most xPath queries start this way.
Thus, the identifySelectorKind
function could appear as follows:
function identifySelectorKind(selector){
if (selector[0] === "/") return "xPath";
else return "css";
}
I don't require validation for css or xpath selectors; instead, I need a foolproof method to distinguish between the two. Will relying on xPath queries starting with /
while css selectors do not be reliable? Are there alternative approaches or crucial factors to consider?