We all know that there are many different selector combinations one can use to create a unique wrapped set of jQuery elements.
Does a tool (plugin, extension, etc) exist that allows the user to visually click on any section of the DOM (similar to Firebug's inspect feature) and auto-suggests relev开发者_StackOverflow社区ant potential selectors that match that element?
The tool would have internal knowledge of jQuery selectors (CSS selectors fall short) and would take into account the surrounding elements + the DOM to provide 10-20 helpful selector suggestions.
Here is a start point to play around with what you need (i hope) or just to understand:
JSFIDDLE DEMO
$("body").click(function(event) { // if you are not interested on 'body' himself use: $("body>*")
// QUESTIONS:
var Q_qwer = 'Not a parent';
var Q_children = 'Not a children';
var Q_last = 'Not last';
var Q_first = 'Not first';
//#
if ($(event.target).children().size() > 0) {
myChildren = $(event.target).children();
var Q_parent = myChildren[0].nodeName + ' (ID: ' + myChildren[0].id + ' || CLASS: ' + myChildren[0].className + ' )';
}
if ($(event.target).parent().size() > 0) {
myParent = $(event.target).parent();
var Q_children = myParent[0].nodeName + ' (ID: ' + myParent[0].id + ' || CLASS: ' + myParent[0].className + ' )';
}
if ($(event.target).is(':last-child')) {
Q_last = 'LAST!' ;
}
if ($(event.target).is(':first-child')) { // or use: $(event.target).index() == 0
Q_first = 'FIRST!' ;
}
$("#log").html(' event.target: ' + event.target +
' <br> nodeName: ' + event.target.nodeName +
' , Tag: ' + event.target.tagName +
' <br> ID: ' + event.target.id +
' <br> Class: ' + event.target.className +
' <br> Href: ' + event.target.href +
' <br> Value: ' + event.target.value +
' <br> Children of: ' + Q_children +
' <br> Parent of: ' + Q_parent + ' (First children)' +
' <br> Last children?: ' + Q_last +
' <br> First children?: ' + Q_first +
' <br> .index( ' + $(event.target).index() + ')' +
' <br> .eq( ' + $(event.target).prevAll().length + ')' +
' <br> <hr>' + $(event.target).html()
);
});
Hope this helps!
You could try this bookmarklet called SelectorGadget
There is something in the Chrome developer tools that does this. Not fool proof but might be worth a try. If you inspect your Element in the dev tools, in the right panel in the elmements tab (CSS styles) there is a little cog, click it and click "New Style Rule", this adds a new CSS style rule in the style panel with a selector matching your element.
精彩评论