Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select element has class start and end with specific string using jquery?

I got several divs using classes like

  • .wrap-1-addon-1
  • .wrap-2-addon-1
  • .wrap-3-addon-1

I want to select all of them and use if ( $(this).hasClass() ) to check if its one of them. Currently I only do check for a single class. How can I check all of these, for example .hasClass('wrap-*-addon-1')?

Best regards.

like image 741
Marian Rick Avatar asked Feb 01 '17 13:02

Marian Rick


3 Answers

You can combine two jquery Attribute Starts With Selector [name^=”value”] and Attribute Ends With Selector [name$=”value”] to do this work.

$('div[class^="wrap-"][class$="-addon-1"]')

$('div[class^="wrap-"][class$="-addon-1"]').css("color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap-1-addon-1">wrap-1-addon-1</div>
<div class="wrap-2-addon-1">wrap-2-addon-1</div>
<div class="wrap-3-addon-1">wrap-3-addon-1</div>
<div class="wrap-3-addon-2">wrap-3-addon-2</div>
like image 181
Mohammad Avatar answered Sep 19 '22 09:09

Mohammad


You can use starts with selector:

$('div[class^="wrap"]')

JsFiddle demo

like image 43
urbz Avatar answered Sep 20 '22 09:09

urbz


You could use .is() which support multiple classes, unfortunately .hasClass() works only for one class at a time.

Example:

element.is('.wrap-1-addon-1, .wrap-2-addon-1, .wrap-2-addon-1')
like image 24
Radex Avatar answered Sep 21 '22 09:09

Radex