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>
2
  • 1
    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 problem Commented Jul 28, 2015 at 7:27
  • what is an a XY problem? Commented Jul 28, 2015 at 11:12

4 Answers 4

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>

Sign up to request clarification or add additional context in comments.

Comments

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/

Comments

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

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.