Skip to content

Instantly share code, notes, and snippets.

@guozi
Last active January 14, 2022 07:11
Show Gist options
  • Save guozi/d26ca6692584d93bee43648742a751fa to your computer and use it in GitHub Desktop.
Save guozi/d26ca6692584d93bee43648742a751fa to your computer and use it in GitHub Desktop.
[Js根据xpath获取元素或者元素值]
function _x(STR_XPATH) {
var xresult = document.evaluate(STR_XPATH, document, null, XPathResult.ANY_TYPE, null);
var xnodes = [];
var xres;
while (xres = xresult.iterateNext()) {
// 获取元素
xnodes.push(xres);
// 获取指定元素的值
//xnodes.push(xres.getAttribute('data-cgt-code'));
}
return xnodes;
}
// 使用
console.log(_x('//ul[@id="newul"]/li'));
function _x() {
var xresult = document.evaluate('//ul[@id="newul"]/li', document, null, XPathResult.ANY_TYPE, null);
var xnodes = new Map();
var xres;
while (xres = xresult.iterateNext()) {
xnodes.set(xres.getAttribute('data-cgt-code'),xres.getAttribute('title'));
}
console.log(xnodes);
array = Array.from(xnodes, ([name, value]) => ({ name, value }));
console.log(array);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment