This solution is better for code reuse:
Include jQuery
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<script>
Create custom selector :attrlength(attr,length)
$.extend(jQuery.expr[':'], {
attrlength: function (el, index, selector) {
var splitted = selector[3].split(',');
var attrName = splitted[0].trim();
var attrLength = parseInt(splitted[1].trim());
var attr = jQuery(el).attr(attrName);
if(attr) return attr.length == attrLength;
return false;
}
});
Testing it out
JS
$(document).ready(function(){
const elements = $(":attrlength(class,4)");
console.log(elements[0]);
});
HTML
<span class="four">Text</span>
<span class="two">Text123</span>
<span class="one">Text123</span>
Output
<span class="four">Text</span>
filter()
but i'm really not sure why you would need that... Whatever you are trying to do, sounds like a XY problem – Dee