Avatar of hankknight
hankknight
Flag for Canada asked on

jQuery: Elements with class name beginning with term

Using jQuery, how can I select all elements that have a class name beginning with "hello"?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo</title>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {
 $('.hello*').each(function(index) {	
  alert($(this).attr('class'));
 });
});

</script>
</head>
<body>

<h1 class="helloH">Heading</h1>
<div class="hello1">1</div>
<div class="hello2">2</div>
<div class="hello3">3</div>
<p class="nomatch">This should not be included</p>
<p class="helloP">ABC</p>
<p class="helloXYZ">XYZ</p>

</body>
</html>

Open in new window

JavaScript

Avatar of undefined
Last Comment
leakim971

8/22/2022 - Mon
leakim971

$('[className^="hello"]').each(function(
hankknight

ASKER
Thanks, but it does not work for me.  Please test this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo</title>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {
 $('[className^="hello"]').each(function(index) {
  alert($(this).attr('class'));
 });
});

</script>
</head>
<body>

<h1 class="helloH">Heading</h1>
<div class="hello1">1</div>
<div class="hello2">2</div>
<div class="hello3">3</div>
<p class="nomatch">This should not be included</p>
<p class="helloP">ABC</p>
<p class="helloXYZ">XYZ</p>

</body>
</html>

Open in new window

ASKER CERTIFIED SOLUTION
leakim971

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
leakim971

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck