With jquery, is there a selector statement that directly gets all DOM objects with an atribute of a particular string-length?
For instance, in the html below only retrieve nodes with class of string-length 3 => results in divs with classes one and two ?
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
A slightly odd requirement, but you can use filter()
to achieve it.
var $divs = $('div').filter(function() {
return this.className.length === 3;
});
-- Apr 2021 Update --
Using ES6 this code can be made shorter still:
let $divs = $('div').filter((i, el) => el.className.length === 3);
There is a cool function from James Padolsey to use a regex for selecting elements.
Example:
// Select all DIVs with classes that are three characters long:
$('div:regex(class,^[a-zA-Z]{3}$)').css("background-color","black");
See full solution at:
https://jsfiddle.net/xtoakxev/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With