views:

306

answers:

3

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.

+2  A: 

You 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);
});
tvanfosson
I don't think that's what he wants. That would limit him to using those inside the event handlers...
Franz
Sure, but you could store the jQuery object itself in a container for use elsewhere. I suppose if you wanted a path you could always simply recurse upward via parent() until you get to the body element.
tvanfosson
What if the page has several p's? The tool's purpose is to create $...
Tony_Henrich
Hmmm... yeah. That depends on what exactly he wants. If he's too lazy too just look the "path" up and write it down all by himself, this won't help him a lot.Then again, the plugin would probably give him the full path, while that is not always practical etc...
Franz
+4  A: 

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!

Derek P.
A: 

You may use also XPather plugin for FF as a little helper in your task.

http://xpath.alephzarro.com/

It shows XPATH of element, that may help you to understand what it is from DOM point of view.

sergionni