troubleshooting Question

JavaScript: Count optgroups of select

Avatar of hankknight
hankknightFlag for Canada asked on
3 Comments2 Solutions1657 ViewsLast Modified:
Using JavaScript, how can I count the number of optgroups of a specific select?

Please do NOT use jQuery for this.

This does NOT work:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />

<select name="StateProvinceList" id="StateProvinceList">
  <option value="">&nbsp; --- Please Select ---</option>
  <optgroup id="USAStates"  label="USA States">
	<option value="AL">Alabama</option>
	<option value="AK">Alaska</option>
	<option value="AZ">Arizona</option>
  <optgroup id="USATerritories" label="USA Territories">
	<option value="AS">American Samoa</option>
	<option value="GU">Guam</option>
  <optgroup id="USAForces" label="USA Armed Forces">
	<option value="AA">Armed Forces Americas</option>
	<option value="AP">Armed Forces Pacific</option>
  <optgroup id="Canada" label="Province / Territory">
	<option value="AB">Alberta</option>
	<option value="BC">British Columbia</option>

<select name="zzz" id="zzz">
  <option value="">&nbsp; --- Please Select ---</option>
  <optgroup id="x"  label="x">
	<option value="1">1</option>
	<option value="2">2</option>

<script type="text/javascript">

  var StateProvinceList = document.getElementById('StateProvinceList');
  alert('Number of options: ' + StateProvinceList.options.length);
  alert('Number of groups: ' + StateProvinceList.optgroups.length);


David S.
Consultant & Challenge Subduer
Join our community to see this answer!
Unlock 2 Answers and 3 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 3 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros