开发者

jQuery unique elements

开发者 https://www.devze.com 2022-12-21 10:28 出处:网络
http://api.jquery.com/jQuery.unique/ lets you get only unique elements. Is there I can find out if an element is already in the list or not.

http://api.jquery.com/jQuery.unique/ lets you get only unique elements. Is there I can find out if an element is already in the list or not.

list = $('#container p a');

elem = $('#container div a:first');

Is there a way to find out if elem is already in the list or n开发者_如何学Cot.


You can use index():

if (list.index(elem[0]) == -1) {
  ...
}

It will return -1 if the element isn't in the collection.


If you want to operate only on elements in the list that don't match the other selector, you can do:

var difference = $(list).not('#container div a:first');

If you want to find the set of elements that match both you can do:

var intersect = $(list).filter('#container div a:first');


jQuery has some utilities that might help -

Use elem.each() to loop through the second array, on each entry do a this.inArray() check against list.makeArray() - so you're look at each item in the second array, and seeing if it's present in the first one, at which point you can perform whatever operation you're looking for.

I almost want to say that there might be some sort of selector magic you could build into one line of code, but I don't know it off the top of my head.

0

精彩评论

暂无评论...
验证码 换一张
取 消