I was wondering if such a tool exists in a browser. You select any item on the page like a <p>
tag nested in several div's and the tool creates a JQuery selector for it which I can copy and use in my Javascript function.
views:
306answers:
3You can always use the element itself as a selector. For example, using $(this) inside a click handler wraps the current element inside a jQuery object.
$('p').click( function() {
var html = $(this).html();
... more computing...
});
If you need a string selector for a particular element, that's going to be harder. You'd have to recurse upward using parent() and prev() (to get offsets for similar elements at each level) unless the element itself has an id -- then you could just use it.
You may be better off creating a unique class that you can assign and referencing it that way.
var counter = 0;
$('p').click( function() {
var uniq = 'paragraph-' + counter;
++counter;
$(this).addClass(uniq);
});
I think you should check out SelectorGadget. It is a JavaScript bookmarklet that allows you to interactively select items on the page and spits you out the exact targeting selector based on the DOM.
Its pretty advanced, watch the screencast!
You may use also XPather plugin for FF as a little helper in your task.
It shows XPATH of element, that may help you to understand what it is from DOM point of view.