Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery select by attribute length

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>
like image 497
mmzc Avatar asked Jan 07 '23 21:01

mmzc


2 Answers

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);
like image 130
Rory McCrossan Avatar answered Jan 29 '23 23:01

Rory McCrossan


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/

like image 32
Bjoerg Avatar answered Jan 30 '23 01:01

Bjoerg