The browser ouput of the script below is going to be:
The browser ouput of the script that follows is going to be
If there was a break or return statement under the statements for each case, the function would have been exited immediately and processing stopped. In the examples above, this only works for the first sample since the first match was found at the end of the switch statement block.
Using the Switch Statement in Bulk Formatting Elements
Below we have a bulk of span elements and we’d like to set the text colors without having to type in the id or CSS attributes. We would use the Document Object Model (DOM) object and collection method to access each element and set the style attributes for each element. The script below assigns an id, color and border attribute to each span element that’s inside the blockquote element. The color attribute depends on the id of each span element.
1Function doThis() has a match in the first position of the switch statement. This is to illustrate that execution begins here and continues through the remaining case matches; since there are no break or return statements.
2Function doThis2() has a match in the last position of the switch statement; showing that it is the only case match and so the only formatting that is applied.
Paste the code in your editor to see …
This is span 1
This is span 2
This is span 3
This is span 4
This is span 5
The examples above did not show any break or return statements in order to illustrate how the switch statement works. If we wanted to to break out of the switch loop, we would add a break or return statement as the last line of: statements, function calls or methods under each case’s set of statements.
Here’s a snippet:
case “span0” :
….some statement ;
….another statement ;
This post is part of the series: Web Design using DHTML and the DOM
Creating web sites with DHTML based on the DOM can increase server performance, lower bandiwdth utilization and solve most cross-browser compatibility issues.
- Validating Input at the Client: Check for blank or required fields
- Validating Input at the Client: trim the field
- Validating Input at the Client: check numeric value fields
- Leveraging CSS Styles
- DOM getElementsByTagName Method for Bulk Element Formating