File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

jquery selecting an element query

 
Vishal Hegde
Ranch Hand
Posts: 1077
Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do they mean the same thing? if yes in the 4 th line why array[0] is being used? because someElement is ID as # is prefixed to it right? and someElement cannot be duplicate.

 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64182
83
IntelliJ IDE Java jQuery Mac Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They do the the same thing, but do not mean the same thing.

The only reason that they do the same thing is the mere fact that an element id can only be used once in a page. If you take the same example, and use a different selector:
They will not do the same thing if there is more than one element with class some-class.

The first statement will apply to all the elements, the second will only apply to the first.

The second statement, by the way, would be considered poor practice. When using jQuery, use jQuery.

The [0] in the second statement takes advantage of the fact the the jQuery wrapped set created by the $() function acts like an array, and so [0] will fetch the first element from the wrapped set if one exists.

It's better to use the .get() wrapper method to fetch an item from the wrapped set.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64182
83
IntelliJ IDE Java jQuery Mac Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One more point:

Even when there is only one element in the wrapped set, the expressions:
are not all the same.

The first returns a jQuery wrapped set that contains the single element.

The second fetches the first element from the wrapped set and returns a reference to that element; not the wrapped set.

The third does the same as the second, but using a method that is generally preferred over array notation.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64182
83
IntelliJ IDE Java jQuery Mac Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another point, with code such as:If the element does not exist, the first format will do nothing, while the second format will result in a JavaScript error.

Bottom line: use jQuery as intended.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic