javascript - Getting path/"unique selector" to HTML object: why it doesn't work? -


i'm trying path object selected user. made code, doesn't work correctly , have no idea why.

here is:

var selobj = window.getselection().anchornode; //chosen html object var currentcheck = selobj; //element name added path var path = ""; //path element while (currentcheck.tagname != "body") {     currentcheck = currentcheck.parentnode;     var addtopath = currentcheck.tagname.tolowercase();      //class     if (currentcheck.classname != "") {         var divideclassnames = currentcheck.classname.replace(/( {2,})/, '').replace(/ *$/, '').replace(/^ */, '').replace(/\ /g, '.');         addtopath += "." + divideclassnames;     }     //id     if (currentcheck.id != "") {         addtopath += "#" + currentcheck.id;     }      //nthchild     var = 0;     var child = currentcheck;     while ((child = child.previoussibling) != null) {         i++;     }     addtopath += ":nth-child(" + + ")";      if(path !== ""){         path = addtopath + " > " + path;     } else {         path = addtopath;     }  } 

you can copy it, highlight text on website , run in browser console.

i highlighted first few words ("the domestic dog") of wikipedia article , got is:

body.mediawiki.ltr.sitedir-ltr.ns-0.ns-subject.page-dog.skin-vector.action-view:nth-child(2) > div.mw-body#content:nth-child(5) > div.mw-body-content#bodycontent:nth-child(9) > div.mw-content-ltr#mw-content-text:nth-child(7) > p:nth-child(6)

using:

$("body.mediawiki.ltr.sitedir-ltr.ns-0.ns-subject.page-dog.skin-vector.action-view:nth-child(2) > div.mw-body#content:nth-child(5) > div.mw-body-content#bodycontent:nth-child(9) > div.mw-content-ltr#mw-content-text:nth-child(7) > p:nth-child(6)") 

in browser console returns no elements (browser can't find it).

in firefox there option "copy unique selector". used on object path want , i've got is:

#mw-content-text > p:nth-child(4) 

as see, there problem "nth-child" (my script returns 6, browser - 4). tried on other sites: everywhere problem nth-child only.

what should change make work correctly?

your problem text node

while ((child = child.previoussibling) != null) {     if (child.nodetype != 3) {       i++;     } } 

you add text node in count nth-child , don't need it. white space in html, between tags, create text node in dom

more info http://www.w3schools.com/jsref/prop_node_nodetype.asp


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -