简体   繁体   中英

How to select elements with a specific array length

In an each function , I search through the DOM for many elements with a specific className . This ClassName, according to its length, will create an array that is long 2 or 4.
I need to select these two type of element separately in order to act differently.
How can I do that?

<div class="foo-1"></div>
<div class="foo-1"></div>
<div class="foo-1-boo-2"></div>

jQuery

$( '[class*=foo-]' ).each(function() {
  var foo = $( this );
  var fooArray = foo.attr( 'class' ).split( '-' );
  var arrayLength = fooArray.length;
});

the console will return that there are 3 elements , two of them have length 2 and one 4 .
I need to separate these two results in order to act differently as they were variables.
I need something like:

var caseA = (foo with an arrayLength === 2);
var caseB = (foo with an awwayLength === 4);

One possible way is to use .filter method with a function as an argument:

var elements = $('[class*=foo-]'),
    caseA = elements.filter(function() {
        return this.className.split('-').length === 2;
    }),
    caseB = elements.filter(function() {
        return this.className.split('-').length === 4;
    });

console.log(caseA.length, caseB.length);

I'm guessing you want these as jQuery sets instead of arrays so you can easily manipulate them en masse with jQuery. So this will do it:

var caseA = $('[class*=foo-]').filter(function() {
   return $(this).attr("class").split("-").length === 2;
});

var caseB = $('[class*=foo-]').filter(function() {
   return $(this).attr("class").split("-").length === 4;
});

If you have tons of elements and it proves to be slow you can optimize this slightly by making it more complex and using one each instead of filter. But I wouldn't bother until it proves to be necessary.

Another possible way is to just use a conditional statement -

$('[class*=foo-]').each(function () {
    var foo = $(this);
    var fooArray = foo.attr('class').split('-');
    var arrayLength = fooArray.length;
    (2 == arrayLength ? console.log('to do something') : '');
    (4 == arrayLength ? console.log('do something for') : '');
});

I mixed two solutions in the comment of this post:

var caseA = col.filter(function() {
  return this.className.split( '-' ).length === 2;
});
var caseB = col.filter(function() {
  return this.className.split( '-' ).length === 4;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM