實現一個函數,生成某個DOM元素的xpath,主要包含兩部分:標籤層級和兄弟元素中的順序html
功能以下:node
<body> <ul> <li> <span>1</span> </li> <li> <span>2</span> <span>3</span> <span id="span_3">4</span> </li> </ul> </body>
若是傳入id="span_3"的元素,生成的xpath是body>ul[0]>li[0]>span[2] 實現以下文js代碼,需引入jqueryjquery
function getPath($ele) { function path(el, obj) { if (el[0].nodeName === 'BODY') { obj['BODY'] = '' return obj } else if (el.parent()[0].nodeName === 'BODY') { var children = el.parent().children() for (var i = 0, len = children.length; i < len; i++) { if (el[0] === children[i]) { obj[el[0].nodeName] = i } } obj['BODY'] = '' return obj } else { var children = el.parent().children() for (var i = 0, len = children.length; i < len; i++) { if (el[0] === children[i]) { obj[el[0].nodeName] = i } } path(el.parent(), obj) } } let o = {}; path($ele, o) var str = '' for (var k in o) { if (o[k] === '') { str += k + "&" } else { str += k + "[" + o[k] + "]" + "&" } } return str.trim().split("&").reverse().join(">").slice(1).toLowerCase() } // 使用 console.log(getPath($('#test')))