javascriptjqueryattributesstring-length

Select element by attribute value length using jQuery


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>

Solution

  • 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>