I have a couple of div containers with similar classes. The pattern for start and end is the same for field-*-preview. I need a wildcard for the middle.
This also works so far, but with multiple classes it is the case that if there is another class behind the class (field-*-preview), this element is not recorded.
var sel = $('[class*=field-][class$=-preview]').length
console.log(sel)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field-1-preview row-1 col-md-4"></div>
<div class="field-2-preview"></div>
<div class="field-3-preview"></div>
<div class="field-4-preview"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
How about:
const sel = $('[class]').filter(function() {
const pattern = /^field\-. \-preview$/;
for (const value of this.classList) {
if (pattern.test(value)) {
return true;
}
}
return false;
}).length;
console.log(sel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field-1-preview row-1 col-md-4"></div>
<div class="field-2-preview"></div>
<div class="field-3-preview"></div>
<div class="field-4-preview"></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
With this selector [class$=-preview]
you are searching for elements that have the attribute class
ending with -preview
. You should combine two selectors searching for elements having the class
attribute that contains both field-
and -preview
.
var sel = $('[class*=field-][class*=-preview]').length
console.log(sel)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field-1-preview row-1 col-md-4"></div>
<div class="field-2-preview"></div>
<div class="field-3-preview"></div>
<div class="field-4-preview"></div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Note that it could match elements you don't want to select such as :
<div class="field-foo bar-preview"></div>