Sometimes you want to link to a certain part of a web page. That’s great and works well if its a nice site that clearly defines anchor tags to link to, but what if there isn’t?
Today I just remembered something and I thought that I saw something earlier with a xpath URL hash. I googled it and couldn’t find anything native to the browser (please correct me if I’m wrong) but found this script: http://userscripts.org/scripts/show/8924 which is basically what I was thinking about. But it was allegedly hard to make those URLs, so I thought why not make a bookmarklet to make linking to those URLs simple? So I quickly hacked this together
XPathLink (Just drag it over to your bookmarks bar as with any other bookmarklet). To use, just click on the bookmark, and click on the element you want to link to. You should see the URL will update with a xpath hash showing you the copy-pastable link to that element. The code is quite simple and should work on Firefox, Chrome and all the other browsers (maybe even IE) but the ability to auto-scroll and actually use the links is only available to Firefox and potentially Opera and Chrome.
And I’m working on a Chrome Extension for the original userscript (which should work with Chrome’s userscript support, but I’m going to try packaging it as a chrome extension file) But sadly chromium for linux isnt up to speed especially with extension development.
The source can be found http://gist.github.com/223708.
Update: Fixed the link for the path and added some stuff. Update 2: Fixed bookmarklet, now scrolls to clicked, executes only once, prevents default
I came across your script, and converted it to a jQuery plugin for a specific need that I had. Here’s the script:
(function($){$.fn.xpath=function(){ var el=this;for(var e=””,c=$_(el)[0];c&&c.nodeType==1;c=c.parentNode){var b=$_(c.parentNode).children(c.tagName).index(c)+1;b>1?(b=”["+b+"]“):(b=””);e=”/”+c.tagName.toLowerCase()+b+e;}return e;};})(jQuery);
Using this, I can reference the xPath of any element on a page by calling $(“#SomeElement”).xpath();
Thanks
Nice (and useful) bookmarklet but, once you have the url updated, how do you use it?
(I can’t use it as a valid link)
Thk you