Select all 'a' elements from a page?

2019-09-14 20:10发布

问题:

I want to select a link with some text then I put:

$("a[text='some text']")

But didn't work, then I want to test selecting all links from a page.

$("a")

But this jquery select instruction only gave me the first or maybe the most important link of the page.

Why?

An example is here:

Thanks in advance.

回答1:

Coding Horror does not make use of jQuery: there is no reference to the library in the source. If you tried jQuery('a') instead, you would receive an error stating that jQuery is not defined or it is not a function.

The reason $('a') works anyway, but only returns the first element, is because $ is defined within Chrome's developer console, but as an alias of document.querySelector. This native method only returns the first matching element if any, unlike document.querySelectorAll which returns all matching elements.

There is a different command aliased to document.querySelectorAll and that is $$. Calling either one will yield all (256) elements matching the selector string:

> $$('a')
NodeList[256]

> document.querySelectorAll('a')
NodeList[256]

Both $ and $$ are documented here.



回答2:

the page doesnt actually have jQuery on it. Type $ or window.$ into the console. by typing $('a') you are using the chrome Command Line API. https://developers.google.com/chrome-developer-tools/docs/commandline-api