14
Aug
2009

Given 'n' number of dynamically generated elements on a page, all starting with a particular string (e.g. "menu_1, menu_2, menu_3 ... menu_n"), and without knowing how many there are, use jQuery to access these elements.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<title>
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>

	<script type="text/javascript">
		$(function() {
			$('div[id^="menu_"]').each(function() {
				alert(this.id);
			});
		});
	</script>
</head>

<body>

<div id="menu_1">menu 1</div>
<div id="menu_2">menu 2</div>
<div id="menu_3">menu 3</div>
<div id="menu_4">menu 4</div>
<div id="menu_5">menu 5</div>

</body>
</html>

Using jQuery selectors, you can access all <div> elements on a page via ('div').

jQuery also makes use of attribute selectors, which allow you to search for a particular element based on a given attribute. For example, to find all <div> elements with an id="menu" attribute:

$('div[id="menu"]')

However, in this case we only want <div> elements whose id begin with the string "menu_". jQuery can do the following attribute filter (note the use of the caret (^) character):

$('div[id^="menu_"]')

Additionally, jQuery supports the following attribute filters:

$('div[id!="SomeString"]'); // id not equal to "SomeString"

$('div[id$="SomeString"]'); // id ends with "SomeString"

$('div[id*="SomeString"]'); // id contains "SomeString"

Comments (2) | 3653 Views

Comments

Add Comment | Subscribe to Comments

  1. Matt Quackenbush's Gravatar

    # Posted Matt Quackenbush on 8/15/09 12:20 PM

    Excellent post. Love the inclusion of the filtering techniques. :-)

  2. Lola LB's Gravatar

    # Posted Lola LB on 9/19/09 2:33 PM

    Wow . . . this is really useful to know that grep can be used . . .

Add Comment