JavaScript jQuery Basics Working with jQuery Collections jQuery-Specific Selectors

Ryan Doran
Ryan Doran
7,499 Points

White Space in $('a[href$ = "pdf"]') throws an error

Interesting:

This will hide the pdf files:

const $odd = $('a:odd');
const $secureLinks = $('a[href^="https://"]');
const $pdfs = $('a[href$="pdf"]');
$pdfs.hide(); 

but this will not:

const $odd = $('a:odd');
const $secureLinks = $('a[href^="https://"]');
const $pdfs = $('a[href$ = "pdf"]');
$pdfs.hide();

Apparently, the white space between the href$, the equal sign (=), and then the quotes throws an error:

JavaScript $('a[href$ = "pdf"]')

  Error: Syntax error, unrecognized expression: a[href$ = "pdf"]

1 Answer

Steven Parker
Steven Parker
173,682 Points

White space in general won't cause a problem, but here it was separating the characters of a single operator. The "match at the end" operator is "$=" and can only be recognized by the system when both characters are adjacent. And the name of the attribute being tested is "href", not "href$".

I would expect to see the following behavior:

const $pdfs = $('a[href$ = "pdf"]');  // this would cause a syntax error
const $pdfs = $('a[href $= "pdf"]');  // but this should work
Ryan Doran
Ryan Doran
7,499 Points

Awesome info, that clears up a great deal, thanks Steven.