jQuery Expand All

Here’s another lunchtime jQuery snippet as the last one proved semi-popular. This one came about today as I needed to expand on an existing expand/collapse functionality to allow users to expand or collapse all of the objects with this functionality.

What had already been done was set a jQuery function to react on the presence of the .expanded class. The way it works is very simple, jQuery grabs all the elements with the .expandable class and then using the :first selector it tests the first one to see whether it is expanded or not. Then depending on the outcome it applies or removes the .expanded class.

function toggle_expand_all() { 
	if ($('.expandable:first').is('.expanded')) {
	} else {

The headache with this snippet was my misunderstanding the jQuery.addClass and jQuery.removeClass pieces, originally I had “.addClass(‘.expanded’)” and that add the class ‘..expanded’ – Oops.

I opted to use .is as opposed to the .hasClass simply for it’s short length, no real reason here as both work by my understanding.