JQuery is selected by attribute length

With jquery, is there a selector statement that directly gets all DOM objects with an attribute of a specific string length?

For example, in the html below, only nodes with a string length class of 3 => are extracted, displaying divs with classes one and two?

<div class="one"></div> <div class="two"></div> <div class="three"></div> 
+4
source share
3 answers

A bit of a strange requirement, but you can use filter() to achieve it.

 var $divs = $('div').filter(function() { return this.className.length === 3; }); 
+6
source

There is a great feature from James Padolsey to use regex to select items.

Example:

 // Select all DIVs with classes that are three characters long: $('div:regex(class,^[a-zA-Z]{3}$)').css("background-color","black"); 

View full solution at:

https://jsfiddle.net/xtoakxev/

+2
source

Rory, of course, has a more elegant solution, but here's what I did when I had a similar requirement.

 $(function () { var a = []; $div = $('div').each( function(i , el){ return ($(this)[0].className.length === 3) ? a.push($(this)) : null; }); }); 
0
source

All Articles