Thanks DaveyErwin. However I can only get it to work with valid XML/XHTML. If I use it on other HTML fragments (e.g. containing
<br> rather than
<br />) then it doesnt work. There doesnt seem to be a mime type for HTML for this function. (I'm using Firefox only).
I managed to find a solution for CSS selectors but it seems strange there is not an equivalent for xPath. See below..
Code:
var stg = "<div>The best-laid<br> schemes o' <span>mice</span> an' men</div>";
var newDiv = document.createElement("div");
newDiv.innerHTML = stg;
//this works
console.log(newDiv.querySelectorAll("span")[0].textContent);
//this doesnt work
var recordNodes = newDiv.evaluate(
".//span",
newDiv,
null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
null );
console.log(recordNodes.snapshotLength);
The mozilla function
nsIScriptableUnescapeHTML.parseFragment() sounds like it might do the job but I cant get .evaluate() to work on it either (and the documentation is pretty slim).