user2142938
user2142938

Reputation: 69

Selecting an element where selector finds in a specific class of element

I have the following structure of div tags and each div tag has multiple classes like :-

<div>

     <div class="jsh-a_train_hotel_amsterdam info js-multiple"></div>

     <div class="jsh-info info js-multiple"></div>

     <div class="jsh-myinfo info js-single"></div>

</div>

Now I want to find div tags which have class name starting with "jsh-" and also the class that starts with "jsh-" should have a substring "info" in it.

So the result should be the following :-

<div class="jsh-info info js-multiple"></div>
<div class="jsh-myinfo info js-single"></div>

(Reason: Because the above 2 div tags have classes jsh-info and jsh-myinfo which satisfies the condition that the element class name should have "jsh-" and the substring in the "jsh-" class name value should have string "info" in it)

Upvotes: 0

Views: 86

Answers (2)

Ejaz
Ejaz

Reputation: 8872

Try this

var elems = $('div[class^="jsh"]').filter(function(){
    return $(this).attr('class').match(/jsh[^ ]info/)
});

Or better use following as jsh-info can occur anywhere in class attribute value

var elems = $('div[class*="jsh"]').filter(function(){
    return $(this).attr('class').match(/\s*jsh[^ ]info/)
});

Update

A you don't need to apply any jquery functions on the elements inside filter(), converting a DOM element to a jQuery object is not needed. So you can use

return this.className.match(/\s*jsh[^ ]*info/)

instead of

return $(this).attr('class').match(/\s*jsh[^ ]info/)

Update 2

If you don't want to hardcode info and want to replace it with a variable, you can do as follows

var theVar = 'info';
$('div[class*="jsh"]').filter(function () {
    return this.className.match(new RegExp('jsh[^ ]*' + theVar, 'gi'))
})

Upvotes: 1

chickpeas
chickpeas

Reputation: 443

Try something like $('div[class^="jsh-"]').filter('div[class*="info"]') the first selector is start with the second is contains.

Upvotes: 0

Related Questions