16

There is this jQuery which seems to look for all elements with id="scuba", but then it uses attr() to pull the id out? Could "scuba" be part of the id and attr pulls the entire id out? I've never seen the $ inside an attribute selector, just outside like the example below.

$('*[id$=scuba]').attr('id')

So my questions are:

  1. What does the $ or $= do in this example
  2. What does this code do?
Boaz
  • 19,892
  • 8
  • 62
  • 70
Bradley Oesch
  • 763
  • 10
  • 22

2 Answers2

25

The dollar sign

The first $ is a shorthand for the jQuery() function, the jQuery object constructor.

In other words, it's a variable called $ that's been assigned a function called jQuery, as can been seen in the unminified version of the jQuery source: window.jQuery = window.$ = jQuery;

The dollar-equals sign

The second $ is part of a jQuery selector called Attribute Ends With Selector . When used in an attribute selector, $= is a logical operator that literally means "true if the left-hand value ends with the right-hand value".

What this script actually does

Overall, this snippet first selects any element with an id attribute ending in scuba. It then retrieves the id value of the first element from the resulting jQuery object.

Boaz
  • 19,892
  • 8
  • 62
  • 70
  • Sorry about the simple question, I didn't know what the term was called and didn't realize that those sorts of selectors existed. Thank you! – Bradley Oesch Apr 11 '13 at 14:18
  • 2
    @BradleyOesch IMHO, I don't think it's "simple". If you don't know what to search, it's not that "simple" to get results. Not to mention that in the case of `$` that's even more difficult. – Boaz Apr 11 '13 at 14:20
  • 3
    This is now the first Google result for `jquery dollar equals`, so I'm glad someone answered :D – Pabbles Oct 28 '13 at 17:12
2

This code selects all DOM elements that have id attributes that end in scuba and returns their id values.

I'm pretty sure it's a better idea to include quotes around scuba, though.

Wim Ombelets
  • 5,097
  • 3
  • 39
  • 55