jQuery: Finding partial class name [duplicate]

Original Answer

You can do some simple partial checking with

$('[class^="value"]') <-- starts with string
$('[class$="value"]') <-- ends with string
$('[class~="value"]') <-- I believe this is the contains string version
$('[class*="value"]') <-- is what you would use to match an element containing the given substring

Additional Information

You can reference https://api.jquery.com/category/selectors/ for some documentation on some selectors the api has explinations for. However, I’ll include a few of them here.

  • Starts With
console.log( $('[class^="test"]').get() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test1 example1"></div>
<div class="example2 test2"></div>

This selector will find elements that have an attribute that starts with the text. Note that the result does not include both elements. This is because the literal class attribute for the second one does not start with test. It starts with example. The starts with selector does not evaluate against each word in the attribute. It goes off the entire attribute value.

  • Ends With
console.log( $('[class$="t2"]').get() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test2 example1"></div>
<div class="example2 test2"></div>

A similar operation is performed for the ends with selector. The entire attribute value is evaluated for the conditional, not each class.

  • Contains String
console.log( $('[class*="test"]').get() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test1 example1"></div>
<div class="example2 test2"></div>

The contains string version does look for the existance of the string any where in the attribute, regardless of if it is a partial or full value.

  • Contains Word
console.log( $('[class~="test"]').get() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test1 example1"></div>
<div class="example2 test2"></div>
<div class="example test"></div>

The contains word selector is similar to the contains text selector, with one distinction. The text must be an entire word, not partial text. So it looks for a string in the value that has a space on both sides of it, unless it is at the beginning or end of the value, with a space on the opposite side to make it a non-partial value.

Leave a Comment