hh54188
hh54188

Reputation: 15646

How can I select different values in array variable,and add to another variable in jquery?

Suppose I have select something:

var $nodeAll = $('.sortable');

then I want select some from them,and add them to another variable named $node,what I want select is the parent don't have a class named 'node':

$nodeAll.each(function () {
        if ($(this).parents('.node').length == 0) {
            //var $node=? what should I do?
        }
});

thank you

Upvotes: 1

Views: 67

Answers (2)

jfriend00
jfriend00

Reputation: 707876

First off, you can't have more than one element with an id="sortable", so I will assume that you're going to change that to a class="sortable".

You use either jQuery .filter() with a custom filter function or you can use .not().

Using .not():

var $nodeAll = $('.sortable');
var $nodeLess = $('.node .sortable');
var $nodeFree = $nodeAll.not($nodeLess);

Using .filter() with a custom function:

var $nodeAll = $('.sortable');
var $nodeFilter = $nodeAll.filter(function() {
    return($(this).parents('.node').length == 0);
});

If you know that the .sortable item will never have .node itself, then this is a little more efficient than the previous version as .closest() can be more efficient than .parents(), but .closest() will look on the starting node first, whereas .parents() starts with the first parent and doesn't look at the current node first:

var $nodeAll = $('.sortable');
var $nodeFilter = $nodeAll.filter(function() {
    return($(this).closest('.node').length == 0);
});

Upvotes: 3

elclanrs
elclanrs

Reputation: 94131

ids must be unique so it makes little sense to iterate var $nodeAll = $('#sortable') with each(). Use a class of .sortable and instead of each() you could use filter() to reduce the collection of objects to the ones that meet a certain condition.

Upvotes: 2

Related Questions