javascript - Get CSS path from Dom element -
i got function csspath :
var csspath = function (el) { var path = []; while ( (el.nodename.tolowercase() != 'html') && (el = el.parentnode) && path.unshift(el.nodename.tolowercase() + (el.id ? '#' + el.id : '') + (el.classname ? '.' + el.classname.replace(/\s+/g, ".") : '')) ); return path.join(" > "); } console.log(csspath(document.getelementsbytagname('a')[123]));
but got :
html > body > div#div-id > div.site > div.clearfix > ul.choices > li
but totally right, should :
html > body > div#div-id > div.site:nth-child(1) > div.clearfix > ul.choices > li:nth-child(5)
did have idea implement in javascript ?
to right element, need use :nth-child()
or :nth-of-type()
selectors not uniquely identify element. try this:
var csspath = function(el) { if (!(el instanceof element)) return; var path = []; while (el.nodetype === node.element_node) { var selector = el.nodename.tolowercase(); if (el.id) { selector += '#' + el.id; } else { var sib = el, nth = 1; while (sib.nodetype === node.element_node && (sib = sib.previoussibling) && nth++); selector += ":nth-child("+nth+")"; } path.unshift(selector); el = el.parentnode; } return path.join(" > "); }
you add routine check unique elements in corresponding context (like title
, base
, caption
, etc.).
Comments
Post a Comment