Iterating over jQuery and non-jQuery Objects

jQuery provides an object iterator utility called $.each() as well as a jQuery collection iterator: .each(). These are not interchangeable. In addition, there are a couple of helpful methods called $.map() and .map() that can shortcut one of our common iteration use cases. link $.each()$.each() is a generic iterator function for looping over object, arrays, … Continue reading

The jQuery Object

When creating new elements (or selecting existing ones), jQuery returns the elements in a collection. Many developers new to jQuery assume that this collection is an array. It has a zero-indexed sequence of DOM elements, some familiar array functions, and a .length property, after all. Actually, the jQuery object is more complicated than that. link … Continue reading

Using jQuery’s .index() Function

.index() is a method on jQuery objects that’s generally used to search for a given element within the jQuery object that it’s called on. This method has four different signatures with different semantics that can be confusing. This article covers details about how to understand the way .index() works with each signature. link .index() with … Continue reading

Utility Methods

jQuery offers several utility methods in the $ namespace. These methods are helpful for accomplishing routine programming tasks. For a complete reference on jQuery utility methods, visit the utilities documentation on api.jquery.com. Below are examples of a few of the utility methods: link $.trim()Removes leading and trailing whitespace: 1 2 // Returns “lots of extra … Continue reading

Working with Selections

link Getters & SettersSome jQuery methods can be used to either assign or read some value on a selection. When the method is called with a value as an argument, it’s referred to as a setter because it sets (or assigns) that value. When the method is called with no argument, it gets (or reads) … Continue reading

How do I determine the state of a toggled element?

You can determine whether an element is collapsed or not by using the :visible and :hidden selectors. 1 2 3 var isVisible = $( “#myDiv” ).is( “:visible” ); var isHidden = $( “#myDiv” ).is( “:hidden” ); If you’re simply acting on an element based on its visibility, just include :visible or :hidden in the selector … Continue reading

How do I disable/enable a form element?

You can enable or disable a form element using the .prop() method: 1 2 3 4 5 // Disable #x$( “#x” ).prop( “disabled”, true ); // Enable #x$( “#x” ).prop( “disabled”, false );

Don’t Act on Absent Elements

jQuery won’t tell you if you’re trying to run a whole lot of code on an empty selection – it will proceed as though nothing’s wrong. It’s up to you to verify that your selection contains some elements. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 … Continue reading