Select element by attribute value length using jQuery
Asked Answered
R

4

6

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

For instance, in the HTML below I only want to retrieve nodes with a class value length of 3 characters. The result should be classes .one and .two. How can I do this?

<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
Rianon answered 28/7, 2015 at 7:26 Comment(2)
You can use filter() but i'm really not sure why you would need that... Whatever you are trying to do, sounds like a XY problemDee
what is an a XY problem?Rianon
F
8

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);

-- Aug 2024 Update --

Here's an example using plain JS, without the need for any jQuery:

[...document.querySelectorAll('div[class]')].filter(el => {
  el.classList.toggle('foo', el.className.length === 3);
});
.foo { color: #C00; }
<div class="one">One</div>
<div class="two">Two</div>
<div class="three">Three</div>
Foah answered 28/7, 2015 at 7:27 Comment(0)
F
2

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/

Fortress answered 28/7, 2015 at 9:1 Comment(0)
P
0

Rory certainly has a more elegant solution, but heres something i had done, 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;
      });
});
Proclamation answered 28/7, 2015 at 7:59 Comment(0)
S
0

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>
Sirois answered 12/11, 2021 at 18:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.