Skip to content

Instantly share code, notes, and snippets.

@sjsakib
Last active November 27, 2020 09:13
Show Gist options
  • Save sjsakib/3c4f01ee7011749056d6dce5b0614998 to your computer and use it in GitHub Desktop.
Save sjsakib/3c4f01ee7011749056d6dce5b0614998 to your computer and use it in GitHub Desktop.
Array.prototype.lastOrDefault = function(cond, defaultValue) {
if (!this.length)
return defaultValue;
if (!cond)
return this[this.length - 1];
for (var i = this.length - 1; i >= 0; --i) {
if (cond(this[i]))
return this[i];
}
return defaultValue;
}
;
try {
if (!window.lastElems)
window.lastElems = new Set();
if (!window.lastFullLength)
window.lastFullLength = 0;
function findLinkByTextCached(text) {
let currElems = [...document.querySelectorAll("body *")];
if (lastFullLength !== currElems.length) {
console.log("save", lastFullLength, currElems.length, document.querySelectorAll(`[class*="item_"]`).length);
lastFullLength = currElems.length;
for (let e of currElems) {
if (!window.lastElems.has(e) && e.offsetParent && e.innerText && !["STYLE", "SCRIPT"].includes(e?.tagName))
window.lastElems.add(e);
if (!e.offsetParent)
window.lastElems.delete(e);
}
}
const elemWithText = [...window.lastElems.values()].lastOrDefault((e)=>e.innerText.includes(text));
return elemWithText;
}
function findElemByTextDirect(text) {
return [...document.querySelectorAll("body *")].filter((e)=>e.offsetParent && e.innerText && !["STYLE", "SCRIPT"].includes(e?.tagName)).filter((e)=>e.innerText.includes(text)).splice(-1)[0];
}
function findElemByTextXPath(text) {
const xPath = `//*[text()[contains(.,'${text}')] and not(self::script or self::style)]`;
const it = document.evaluate(xPath, document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
// get the last item of the iterator
let elem = null;
let curElem = it.iterateNext()
while (curElem !== null) {
elem = curElem;
curElem = it.iterateNext();
}
return elem;
}
console.time("findLinkByTextCached");
console.log(findLinkByTextCached("Growth"));
console.timeEnd("findLinkByTextCached");
console.time("findElemByTextDirect");
console.log(findElemByTextDirect("Growth"));
console.timeEnd("findElemByTextDirect");
console.time("findElemByTextXPath");
console.log(findElemByTextXPath("Growth"));
console.timeEnd("findElemByTextXPath");
} catch (e) {
console.log(e);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment