how to make this javascript function output #value in the xpath? - javascript

The code below, produces Xpath. However, it doesn't display #value attribute/property. It is not working very well.
function getXPath(node, path, val) {
path = path || [];
if(node.parentNode) { path = getXPath(node.parentNode, path); }
if(node.previousSibling) {
var count = 1;
var sibling = node.previousSibling
do {
if(sibling.nodeType == 1 && sibling.nodeName == node.nodeName) {count++;}
sibling = sibling.previousSibling;
} while(sibling);
if(count == 1) {count = null;}
} else if(node.nextSibling) {
var sibling = node.nextSibling;
do {
if(sibling.nodeType == 1 && sibling.nodeName == node.nodeName) {
var count = 1;
sibling = null;
} else {
var count = null;
sibling = sibling.previousSibling;
}
} while(sibling);
}
if(node.nodeType == 1) {
if (val){
path.push(node.nodeName.toLowerCase() + (node.id ?
"[#id='"+node.id+"' #value='"+val+"']" :
count > 0 ? "["+count+"]" : ''));
}else{
path.push(node.nodeName.toLowerCase() + (node.id ?
"[#id='"+node.id+"']" : count > 0 ? "["+count+"]" : ''));
}
}
return path;
};

try:
http://mcc.id.au/xpathjs
or
http://xmljs.sourceforge.net/

Related

Dynamically Highlight Words Based on its Dictionary value

I was able to get some help from a previous post where I wanted to highlight words dynamically as a user entered text.
The previous condition would highlight a word if it began with "t", now I want to update this condition to highlight any words that meet a condition based on dictionary values (I call JavaScript's built in object a dictionary).
For example, if I have a dictionary dict = {"test": 5.0, "check": 4.0, "stop": -1.5, "fair": 2.0} how would I have the script highlight words whose value was greater than 2.0?
Failed code:
dict = {"test": 5.0, "check": 4.0, "stop": -1.5, "fair": 2.0}
function highlighter(ev) {
// Get current cursor position
const currpos = getSelectionDirection(ev) !== 'forward' ? getSelectionStart(ev) : getSelectionEnd(ev);
// Change innerHTML to innerText, you
// dont need to parse HTML code here
var content = ev.innerText;
var tokens = content.split(" ");
for (var i = 0; i < tokens.length; i++) {
if (dict[tokens[i][0]] > 2.0) {
tokens[i] = "<mark style='background-color:red; color:white;'>" + tokens[i] + "</mark>";
}
}
ev.innerHTML = tokens.join(" ");
// Set cursor on its proper position
setSelectionRange(ev, currpos, currpos);
}
/* NOT REQUIRED AT ALL, JUST TO MAKE INTERACTION MORE PLEASANT */
.container {
outline: none;
border: 3px solid black;
height: 100px;
width: 400px;
}
<div class="container" onkeypress=highlighter(this) contenteditable>
</div>
<script>
// Usage:
// var x = document.querySelector('[contenteditable]');
// var caretPosition = getSelectionDirection(x) !== 'forward' ? getSelectionStart(x) : getSelectionEnd(x);
// setSelectionRange(x, caretPosition + 1, caretPosition + 1);
// var value = getValue(x);
// it will not work with "<img /><img />" and, perhaps, in many other cases.
function isAfter(container, offset, node) {
var c = node;
while (c.parentNode != container) {
c = c.parentNode;
}
var i = offset;
while (c != null && i > 0) {
c = c.previousSibling;
i -= 1;
}
return i > 0;
}
function compareCaretPositons(node1, offset1, node2, offset2) {
if (node1 === node2) {
return offset1 - offset2;
}
var c = node1.compareDocumentPosition(node2);
if ((c & Node.DOCUMENT_POSITION_CONTAINED_BY) !== 0) {
return isAfter(node1, offset1, node2) ? +1 : -1;
} else if ((c & Node.DOCUMENT_POSITION_CONTAINS) !== 0) {
return isAfter(node2, offset2, node1) ? -1 : +1;
} else if ((c & Node.DOCUMENT_POSITION_FOLLOWING) !== 0) {
return -1;
} else if ((c & Node.DOCUMENT_POSITION_PRECEDING) !== 0) {
return +1;
}
}
function stringifyElementStart(node, isLineStart) {
if (node.tagName.toLowerCase() === 'br') {
if (true) {
return '\n';
}
}
if (node.tagName.toLowerCase() === 'div') { // Is a block-level element?
if (!isLineStart) { //TODO: Is not at start of a line?
return '\n';
}
}
return '';
}
function* positions(node, isLineStart = true) {
console.assert(node.nodeType === Node.ELEMENT_NODE);
var child = node.firstChild;
var offset = 0;
yield {node: node, offset: offset, text: stringifyElementStart(node, isLineStart)};
while (child != null) {
if (child.nodeType === Node.TEXT_NODE) {
yield {node: child, offset: 0/0, text: child.data};
isLineStart = false;
} else {
isLineStart = yield* positions(child, isLineStart);
}
child = child.nextSibling;
offset += 1;
yield {node: node, offset: offset, text: ''};
}
return isLineStart;
}
function getCaretPosition(contenteditable, textPosition) {
var textOffset = 0;
var lastNode = null;
var lastOffset = 0;
for (var p of positions(contenteditable)) {
if (p.text.length > textPosition - textOffset) {
return {node: p.node, offset: p.node.nodeType === Node.TEXT_NODE ? textPosition - textOffset : p.offset};
}
textOffset += p.text.length;
lastNode = p.node;
lastOffset = p.node.nodeType === Node.TEXT_NODE ? p.text.length : p.offset;
}
return {node: lastNode, offset: lastOffset};
}
function getTextOffset(contenteditable, selectionNode, selectionOffset) {
var textOffset = 0;
for (var p of positions(contenteditable)) {
if (selectionNode.nodeType !== Node.TEXT_NODE && selectionNode === p.node && selectionOffset === p.offset) {
return textOffset;
}
if (selectionNode.nodeType === Node.TEXT_NODE && selectionNode === p.node) {
return textOffset + selectionOffset;
}
textOffset += p.text.length;
}
return compareCaretPositons(selectionNode, selectionOffset, contenteditable, 0) < 0 ? 0 : textOffset;
}
function getValue(contenteditable) {
var value = '';
for (var p of positions(contenteditable)) {
value += p.text;
}
return value;
}
function setSelectionRange(contenteditable, start, end) {
var selection = window.getSelection();
var s = getCaretPosition(contenteditable, start);
var e = getCaretPosition(contenteditable, end);
selection.setBaseAndExtent(s.node, s.offset, e.node, e.offset);
}
//TODO: Ctrl+A - rangeCount is 2
function getSelectionDirection(contenteditable) {
var selection = window.getSelection();
var c = compareCaretPositons(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset);
return c < 0 ? 'forward' : 'none';
}
function getSelectionStart(contenteditable) {
var selection = window.getSelection();
var c = compareCaretPositons(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset);
return c < 0 ? getTextOffset(contenteditable, selection.anchorNode, selection.anchorOffset) : getTextOffset(contenteditable, selection.focusNode, selection.focusOffset);
}
function getSelectionEnd(contenteditable) {
var selection = window.getSelection();
var c = compareCaretPositons(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset);
return c < 0 ? getTextOffset(contenteditable, selection.focusNode, selection.focusOffset) : getTextOffset(contenteditable, selection.anchorNode, selection.anchorOffset);
}
</script>
Check below code I used this Cool js lib jQuery highlightTextarea and as per your requirements, I loop through your dict object and push only those words that have a value greater than 2.0.
dict = {"test": 5.0, "check": 4.0, "stop": -1.5, "fair": 2.0}
var words = [];
Object.keys(dict).forEach(function(key) {
if( dict[key] > 2 ){
words.push(key);
}
});
$('textarea').highlightTextarea({
words: words,
caseSensitive: false
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://garysieling.github.io/jquery-highlighttextarea/dist/jquery-ui/themes/smoothness/jquery-ui.min.css">
<link rel="stylesheet" href="http://garysieling.github.io/jquery-highlighttextarea/dist/jquery-highlighttextarea/jquery.highlighttextarea.min.css">
<script src="http://garysieling.github.io/jquery-highlighttextarea/dist/jquery-ui/ui/minified/jquery-ui.min.js"></script>
<script src="http://garysieling.github.io/jquery-highlighttextarea/dist/jquery-highlighttextarea/jquery.highlighttextarea.min.js"></script>
<textarea id="demo-case" cols="50" rows="3" style="background: none;" spellcheck="true">This is a test you can check or stop it will be fair enough.</textarea>
More options here http://garysieling.github.io/jquery-highlighttextarea/#options
Other example here http://garysieling.github.io/jquery-highlighttextarea/examples.html

Divide two Inputs and multiply 100

I have the two functions match and and total working properly. I want the function total project match to divide the first function over the second function multiply times 100. the last function isn't working!
Here is my code so far :
matchContribution.subscribe(function (newValue) {
if (newValue != undefined && newValue != '') {
matchContribution(formatInt(newValue));
var dataValue = Number(matchContribution().replace(/\,/g, ''));
if (dataValue > 999999999999.99 || dataValue < 0) {
matchContribution('');
}
if (loading == false) {
sendCommand('SAVE');
}
}
});
var totalProjectCost = ko.computed(function () {
var total = 0;
var hasUserInput = false;
if (grantRequest() != '' && grantRequest() != undefined) {
hasUserInput = true;
total = total + Number(String(grantRequest()).replace(/\,/g, ''));
}
if (matchContribution() != '' && matchContribution() != undefined) {
hasUserInput = true;
total = total + Number(String(matchContribution()).replace(/\,/g, ''));
}
if (total == 0) {
if (!hasUserInput)
return '';
else
return formatInt('0');
}
else {
if (loading == false) {
sendCommand('SAVE');
}
return formatInt(total);
}
});
var totalProjectMatch = matchContribution()/totalProjectCost();
if(totalProjectMatch>=0)
totalProjectMatch = Math.floor(totalProjectMatch);
else
totalProjectMatch = Math.ceil(totalProjectMatch);
var totalProjectMatch = ko.computed(function () {
var total = 0;
var hasUserInput = false;
if ((grantRequest() != '' && grantRequest() != undefined) && (matchContribution() != '' && matchContribution() != undefined) && (totalProjectCost() != '' && totalProjectCost() != undefined)) {
hasUserInput = true;
total = Number(String(matchContribution()).replace(/\,/g, '')) / Number(String(totalProjectCost()).replace(/\,/g, ''));
total = total * 100;
}
if (total == 0) {
if (!hasUserInput)
return '';
else
return formatInt('0');
}
else {
if (loading == false) {
sendCommand('SAVE');
}
return formatNumber(total);
}
});
I solved the problem! Thanks a lot! Hope that helps other people.

Using for loop to order dependency

var input = [ "KittenService: ", "Leetmeme: Cyberportal", "Cyberportal: Ice", "CamelCaser: KittenService", "Fraudstream: Leetmeme", "Ice: "];
var output = [];
function valid(input) {
for(var i = 0; i < input.length; i++) {
var array = input[i].trim().split(':');
var packageName = array[0].trim();
var dependencyName = array[1].trim();
if(array.length > 1 && dependencyName === '') {
if(output.indexOf(packageName) === -1) {
output.push(packageName);
}
else {
return;
}
}
else if(array.length > 1 && dependencyName !== '') {
if (output.indexOf(dependencyName) === -1) {
output.push(dependencyName);
if(output.indexOf(dependencyName) > -1) {
if(output.indexOf(packageName) > -1) {
continue;
}
else {
output.push(packageName);
}
}
}
else if(output.indexOf(dependencyName) > -1) {
output.push(packageName);
}
}
}
return output.join(', ');
}
valid(input);
I am trying to figure out way to make the output to become
"KittenService, Ice, Cyberportal, Leetmeme, CamelCaser, Fraudstream"
Right it logs
'KittenService, Cyberportal, Leetmeme, Ice, CamelCaser, Fraudstream'
I am not sure how to make all the input with dependencies to pushed before input with dependencies.
Problem was just that you were returning if no package name instead of using a continue.
var input =[ "KittenService: CamelCaser", "CamelCaser: " ]
var output = [];
function valid(input) {
for(var i = 0; i < input.length; i++) {
var array = input[i].trim().split(':');
var packageName = array[0].trim();
var dependencyName = array[1].trim();
if(array.length > 1 && dependencyName === '') {
if(output.indexOf(packageName) === -1) {
output.push(packageName);
}
else {
continue;
}
}
else if(array.length > 1 && dependencyName !== '') {
if (output.indexOf(dependencyName) === -1) {
output.push(dependencyName);
if(output.indexOf(dependencyName) > -1) {
output.push(packageName);
}
}
}
}
return output;
}
console.log(valid(input));

Why will my Javascript not run in IE

Below is my code. It is supposed to filter a table. It functions great in everything but IE. Can you help?
Perhaps there is a missing tag or something. I've been over it a number of times and could really do with someone's help please!
<script type="text/javascript">
function hasPath(element, cls) {
return (' ' + element.getAttribute('pathway')).indexOf(cls) > -1;
}
function hasLevel(element, cls) {
return (' ' + element.getAttribute('level')).indexOf(cls) > -1;
}
function hasBody(element, cls) {
return (' ' + element.getAttribute('body')).indexOf(cls) > -1;
}
function QualificationSearch() {
var imgdiv = document.getElementById("Chosen_Pathway_img");
var p = document.getElementById("PathwaySelect");
var pathway = p.options[p.selectedIndex].value;
if (pathway == "ALLPATHS") {
pathway = "";
imgdiv.src = "/templates/superb/images/QualChecker/pic_0.png"
}
if (pathway == "ES") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_1.png"
}
if (pathway == "HOUSING") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_2.png"
}
if (pathway == "PLAYWORK") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_3.png"
}
if (pathway == "SC") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_4.png"
}
if (pathway == "YW") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_5.png"
}
var a = document.getElementById("AwardingBodySelect");
var awardingBody = a.options[a.selectedIndex].value;
if (awardingBody == "ALLBODIES") {
awardingBody = "";
}
var levelGroup = document.getElementsByName("LevelGroup");
var chosenLevel = ""
for (var g = 0; g < levelGroup.length; g++) {
if (levelGroup[g].checked) {
chosenLevel += levelGroup[g].value + " ";
}
}
if (chosenLevel == undefined) {
var chosenLevel = "";
} else {
var splitLevel = chosenLevel.split(" ");
var levelA = splitLevel[0];
var levelB = splitLevel[1];
var levelC = splitLevel[2];
var levelD = splitLevel[3];
if (levelA == "") {
levelA = "NOLVL"
}
if (levelB == "") {
levelB = "NOLVL"
}
if (levelC == "") {
levelC = "NOLVL"
}
if (levelD == "") {
levelD = "NOLVL"
}
}
var fil = document.getElementsByName("QList");
for (var i = 0; i < fil.length; i++) {
fil.item(i).style.display = "none";
if ((hasBody(fil.item(i), awardingBody) == true || awardingBody == "") && (hasPath(fil.item(i), pathway) == true || pathway == "") && ((hasLevel(fil.item(i), levelA) == true || hasLevel(fil.item(i), levelB) == true || hasLevel(fil.item(i), levelC) == true || hasLevel(fil.item(i), levelD) == true) || chosenLevel == "")) {
fil.item(i).style.display = "block";
}
}
}
</script>
Check your semicolons. IE is far more strict on that kind of stuff than FF.

Javascript get XPath of a node

Is there anyway to return an XPath string of a DOM element in Javascript?
I refactored this from another example. It will attempt to check or there is for sure a unique id and if so use that case to shorten the expression.
function createXPathFromElement(elm) {
var allNodes = document.getElementsByTagName('*');
for (var segs = []; elm && elm.nodeType == 1; elm = elm.parentNode)
{
if (elm.hasAttribute('id')) {
var uniqueIdCount = 0;
for (var n=0;n < allNodes.length;n++) {
if (allNodes[n].hasAttribute('id') && allNodes[n].id == elm.id) uniqueIdCount++;
if (uniqueIdCount > 1) break;
};
if ( uniqueIdCount == 1) {
segs.unshift('id("' + elm.getAttribute('id') + '")');
return segs.join('/');
} else {
segs.unshift(elm.localName.toLowerCase() + '[#id="' + elm.getAttribute('id') + '"]');
}
} else if (elm.hasAttribute('class')) {
segs.unshift(elm.localName.toLowerCase() + '[#class="' + elm.getAttribute('class') + '"]');
} else {
for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling) {
if (sib.localName == elm.localName) i++; };
segs.unshift(elm.localName.toLowerCase() + '[' + i + ']');
};
};
return segs.length ? '/' + segs.join('/') : null;
};
function lookupElementByXPath(path) {
var evaluator = new XPathEvaluator();
var result = evaluator.evaluate(path, document.documentElement, null,XPathResult.FIRST_ORDERED_NODE_TYPE, null);
return result.singleNodeValue;
}
There's not a unique XPath to a node, so you'll have to decide what's the most appropriate way of constructing a path. Use IDs where available? Numeral position in the document? Position relative to other elements?
See getPathTo() in this answer for one possible approach.
Here is a functional programming style ES6 function for the job:
function getXPathForElement(element) {
const idx = (sib, name) => sib
? idx(sib.previousElementSibling, name||sib.localName) + (sib.localName == name)
: 1;
const segs = elm => !elm || elm.nodeType !== 1
? ['']
: elm.id && document.getElementById(elm.id) === elm
? [`id("${elm.id}")`]
: [...segs(elm.parentNode), `${elm.localName.toLowerCase()}[${idx(elm)}]`];
return segs(element).join('/');
}
function getElementByXPath(path) {
return (new XPathEvaluator())
.evaluate(path, document.documentElement, null,
XPathResult.FIRST_ORDERED_NODE_TYPE, null)
.singleNodeValue;
}
// Demo:
const li = document.querySelector('li:nth-child(2)');
const path = getXPathForElement(li);
console.log(path);
console.log(li === getElementByXPath(path)); // true
<div>
<table id="start"></table>
<div>
<ul><li>option</ul></ul>
<span>title</span>
<ul>
<li>abc</li>
<li>select this</li>
</ul>
</div>
</div>
It will use an id selector, unless the element is not the first one with that id. Class selectors are not used, because in interactive web pages classes may change often.
I've adapted the algorithm Chromium uses to calculate the XPath from devtools below.
To use this as-written you'd call Elements.DOMPath.xPath(<some DOM node>, false). The last parameter controls whether you get the shorter "Copy XPath" (if true) or "Copy full XPath".
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
Elements = {};
Elements.DOMPath = {};
/**
* #param {!Node} node
* #param {boolean=} optimized
* #return {string}
*/
Elements.DOMPath.xPath = function (node, optimized) {
if (node.nodeType === Node.DOCUMENT_NODE) {
return '/';
}
const steps = [];
let contextNode = node;
while (contextNode) {
const step = Elements.DOMPath._xPathValue(contextNode, optimized);
if (!step) {
break;
} // Error - bail out early.
steps.push(step);
if (step.optimized) {
break;
}
contextNode = contextNode.parentNode;
}
steps.reverse();
return (steps.length && steps[0].optimized ? '' : '/') + steps.join('/');
};
/**
* #param {!Node} node
* #param {boolean=} optimized
* #return {?Elements.DOMPath.Step}
*/
Elements.DOMPath._xPathValue = function (node, optimized) {
let ownValue;
const ownIndex = Elements.DOMPath._xPathIndex(node);
if (ownIndex === -1) {
return null;
} // Error.
switch (node.nodeType) {
case Node.ELEMENT_NODE:
if (optimized && node.getAttribute('id')) {
return new Elements.DOMPath.Step('//*[#id="' + node.getAttribute('id') + '"]', true);
}
ownValue = node.localName;
break;
case Node.ATTRIBUTE_NODE:
ownValue = '#' + node.nodeName;
break;
case Node.TEXT_NODE:
case Node.CDATA_SECTION_NODE:
ownValue = 'text()';
break;
case Node.PROCESSING_INSTRUCTION_NODE:
ownValue = 'processing-instruction()';
break;
case Node.COMMENT_NODE:
ownValue = 'comment()';
break;
case Node.DOCUMENT_NODE:
ownValue = '';
break;
default:
ownValue = '';
break;
}
if (ownIndex > 0) {
ownValue += '[' + ownIndex + ']';
}
return new Elements.DOMPath.Step(ownValue, node.nodeType === Node.DOCUMENT_NODE);
};
/**
* #param {!Node} node
* #return {number}
*/
Elements.DOMPath._xPathIndex = function (node) {
// Returns -1 in case of error, 0 if no siblings matching the same expression,
// <XPath index among the same expression-matching sibling nodes> otherwise.
function areNodesSimilar(left, right) {
if (left === right) {
return true;
}
if (left.nodeType === Node.ELEMENT_NODE && right.nodeType === Node.ELEMENT_NODE) {
return left.localName === right.localName;
}
if (left.nodeType === right.nodeType) {
return true;
}
// XPath treats CDATA as text nodes.
const leftType = left.nodeType === Node.CDATA_SECTION_NODE ? Node.TEXT_NODE : left.nodeType;
const rightType = right.nodeType === Node.CDATA_SECTION_NODE ? Node.TEXT_NODE : right.nodeType;
return leftType === rightType;
}
const siblings = node.parentNode ? node.parentNode.children : null;
if (!siblings) {
return 0;
} // Root node - no siblings.
let hasSameNamedElements;
for (let i = 0; i < siblings.length; ++i) {
if (areNodesSimilar(node, siblings[i]) && siblings[i] !== node) {
hasSameNamedElements = true;
break;
}
}
if (!hasSameNamedElements) {
return 0;
}
let ownIndex = 1; // XPath indices start with 1.
for (let i = 0; i < siblings.length; ++i) {
if (areNodesSimilar(node, siblings[i])) {
if (siblings[i] === node) {
return ownIndex;
}
++ownIndex;
}
}
return -1; // An error occurred: |node| not found in parent's children.
};
/**
* #unrestricted
*/
Elements.DOMPath.Step = class {
/**
* #param {string} value
* #param {boolean} optimized
*/
constructor(value, optimized) {
this.value = value;
this.optimized = optimized || false;
}
/**
* #override
* #return {string}
*/
toString() {
return this.value;
}
};
Update 2022-08-14: Here is a TypeScript version.
A similar solution is given by the function getXPathForElement on the MDN:
function getXPathForElement(el, xml) {
var xpath = '';
var pos, tempitem2;
while(el !== xml.documentElement) {
pos = 0;
tempitem2 = el;
while(tempitem2) {
if (tempitem2.nodeType === 1 && tempitem2.nodeName === el.nodeName) { // If it is ELEMENT_NODE of the same name
pos += 1;
}
tempitem2 = tempitem2.previousSibling;
}
xpath = "*[name()='"+el.nodeName+"' and namespace-uri()='"+(el.namespaceURI===null?'':el.namespaceURI)+"']["+pos+']'+'/'+xpath;
el = el.parentNode;
}
xpath = '/*'+"[name()='"+xml.documentElement.nodeName+"' and namespace-uri()='"+(el.namespaceURI===null?'':el.namespaceURI)+"']"+'/'+xpath;
xpath = xpath.replace(/\/$/, '');
return xpath;
}
Also XMLSerializer might be worth a try.
function getElementXPath (element) {
if (!element) return null
if (element.id) {
return `//*[#id=${element.id}]`
} else if (element.tagName === 'BODY') {
return '/html/body'
} else {
const sameTagSiblings = Array.from(element.parentNode.childNodes)
.filter(e => e.nodeName === element.nodeName)
const idx = sameTagSiblings.indexOf(element)
return getElementXPath(element.parentNode) +
'/' +
element.tagName.toLowerCase() +
(sameTagSiblings.length > 1 ? `[${idx + 1}]` : '')
}
}
console.log(getElementXPath(document.querySelector('#a div')))
<div id="a">
<div>def</div>
</div>
I checked every solution provided here but none of them works with svg elements (code getElementByXPath(getXPathForElement(elm)) === elm returns false for svg or path elements)
So I added the Touko's svg fix to the trincot's solution and got this code:
function getXPathForElement(element) {
const idx = (sib, name) => sib
? idx(sib.previousElementSibling, name||sib.localName) + (sib.localName == name)
: 1;
const segs = elm => !elm || elm.nodeType !== 1
? ['']
: elm.id && document.getElementById(elm.id) === elm
? [`id("${elm.id}")`]
: [...segs(elm.parentNode), elm instanceof HTMLElement
? `${elm.localName}[${idx(elm)}]`
: `*[local-name() = "${elm.localName}"][${idx(elm)}]`];
return segs(element).join('/');
}
The difference is it returns *[local-name() = "tag"][n] instead of tag[n] if element is not an instance of HTMLElement (svgs are SVGElement but I decided not to stick with checking only svg).
Example:
Before:
.../div[2]/div[2]/span[1]/svg[1]/path[1]
After:
.../div[2]/div[2]/span[1]/*[local-name() = "svg"][1]/*[local-name() = "path"][1]
Just pass the element in function getXPathOfElement and you will get the Xpath.
function getXPathOfElement(elt)
{
var path = "";
for (; elt && elt.nodeType == 1; elt = elt.parentNode)
{
idx = getElementIdx(elt);
xname = elt.tagName;
if (idx > 1) xname += "[" + idx + "]";
path = "/" + xname + path;
}
return path;
}
function getElementIdx(elt)
{
var count = 1;
for (var sib = elt.previousSibling; sib ; sib = sib.previousSibling)
{
if(sib.nodeType == 1 && sib.tagName == elt.tagName) count++
}
return count;
}
Get xPath by giving a dom element
This function returns full xPath selector (without any id or class).
This type of selector is helpful when an site generate random id or class
function getXPath(element) {
// Selector
let selector = '';
// Loop handler
let foundRoot;
// Element handler
let currentElement = element;
// Do action until we reach html element
do {
// Get element tag name
const tagName = currentElement.tagName.toLowerCase();
// Get parent element
const parentElement = currentElement.parentElement;
// Count children
if (parentElement.childElementCount > 1) {
// Get children of parent element
const parentsChildren = [...parentElement.children];
// Count current tag
let tag = [];
parentsChildren.forEach(child => {
if (child.tagName.toLowerCase() === tagName) tag.push(child) // Append to tag
})
// Is only of type
if (tag.length === 1) {
// Append tag to selector
selector = `/${tagName}${selector}`;
} else {
// Get position of current element in tag
const position = tag.indexOf(currentElement) + 1;
// Append tag to selector
selector = `/${tagName}[${position}]${selector}`;
}
} else {
//* Current element has no siblings
// Append tag to selector
selector = `/${tagName}${selector}`;
}
// Set parent element to current element
currentElement = parentElement;
// Is root
foundRoot = parentElement.tagName.toLowerCase() === 'html';
// Finish selector if found root element
if(foundRoot) selector = `/html${selector}`;
}
while (foundRoot === false);
// Return selector
return selector;
}

Categories