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

Traversing

Once you’ve made an initial selection with jQuery, you can traverse deeper into what was just selected. Traversing can be broken down into three basic parts: parents, children, and siblings. jQuery has an abundance of easy-to-use methods for all these parts. Notice that each of these methods can optionally be passed string selectors, and some … 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

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 );

Optimize Selectors

Selector optimization is less important than it used to be, as more browsers implement document.querySelectorAll() and the burden of selection shifts from jQuery to the browser. However, there are still some tips to keep in mind when selector performance becomes a bottleneck. link jQuery ExtensionsWhen possible, avoid selectors that include jQuery extensions. These extensions cannot … Continue reading