How could I test CSS1-3 selectors to check that they get the correct elements, e.g. with JavaScript (maybe jQuery)?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
The simplest traditional way by far is to not use JavaScript at all, and just set up a test page by hand where you can test selectors to your heart's content. The test cases you see on the Web (like the well-known CSS3.info Selectors Test) are really just souped-up versions hosted online.
But if you're looking for a JavaScript method, you can try the Selectors API. It's available in modern DOM implementations (IE8+ and others) and it provides a JavaScript frontend for querying the DOM for element nodes using CSS selectors, as well as testing CSS selectors natively supported by a given browser.
(For browsers that don't implement the Selectors API, you'll have to rely on jQuery, but remember that it provides support for a different set of selectors than what a browser supports as well as its own non-standard extensions which aren't found in the Selectors spec. An example of using jQuery with Chrome's JavaScript console to test a selector can be found here.)
Call
querySelector()
orquerySelectorAll()
depending on what you want to test, and check the return value (preferably in your browser's developer tools since you're just testing):If matches are found, the former method returns the first
Element
matched while the latter returns all elements matched as aNodeList
.If nothing is found, the former returns
null
while the latter returns an emptyNodeList
.If the selector is invalid, an exception will be thrown which you can catch.
Here are some examples with the command editor (multiline) in Firebug's console on Firefox 10, tested on this very question:
Finding the first
h1
inbody
:Querying descendants of that
h1
element we just found:Testing the
:-moz-any()
pseudo-class in Firefox (:-webkit-any()
in Safari/Chrome):Testing a nonexistent selector (that perhaps many of us wish did exist):
http://selectorgadget.com is quite nice to test and build CSS selectors. Just drag and drop a piece of JavaScript they provide into your bookmarks bar and click it whenever you need.