Swathi
Swathi

Reputation: 323

Find the elements that start with class using jQuery selector

I have the following list of elements.

 <tr id="level_0">
 <tr class="level_0_1">
 <tr class="level_0_2">
 <tr class="level_0_2_1">
 <tr class="level_0_2_2">
 <tr class="level_0_2_3">
 <tr class="level_0_2_3_1">
 <tr class="level_0_2_3_2">

I am trying select all the elements that have class level_0_2_X and not level_0_2_X_X

Using the jQuery "starts with" selector I am able to select all the elements that have class level_0_2_X and level_0_2_X_X

   $("tr[class^='level_0_2_']").show();

Upvotes: 0

Views: 354

Answers (2)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382464

You'd better combine a selector with a filtering function :

$('[id^=level_0_2_]').filter(function(){ return this.id.split('_').length<5 })

If what you want is in fact a filtering on the class, you may use this :

$('[class^=level_0_2_]').filter(function(){
    return this.className.split('_').length<5
})

Upvotes: 6

Amar
Amar

Reputation: 12020

Try using match(). Following must get the job done for you:

$('tr').each(function(){
     if( $(this).attr('id').match(/pattern/) ) {
          $(this).show();
     }
  }

Just use the pattern as required. Also above I have used 'id', you get the 'class' attribute if required and match against that.

Upvotes: 1

Related Questions