How to find elements that are not deeper than the selector?

I am creating a jQuery plugin to manage form collections. The plugin aims to add the add , remove , move up and move down buttons to modify this collection.

  • The root of the node collection always contains a selector, for example .collection .

  • A button can be any as soon as it has a .add class

I implemented the min and max options, so the add and remove buttons disappear accordingly. My problem arises when I try to manage a collection of form collections: how do I select only add buttons that link to the desired collection?

To simplify the task, check out the following HTML code:

 <div class="collection"> <div>something</div> <div>something</div> <div> <div class="add">+</div> </div> <div>something</div> <div class="collection"> <div>something</div> <div>something</div> <div> <div class="add">+</div> </div> <div>something</div> </div> </div> 

Keep in mind that a button can be arbitrary: the assembly is created by the user, and I don’t know where the button can be in dom. By the way, this is deeper than .collection , which is all I know.

How to select all add buttons before the second .collection , but no more?

For those interested, this plugin is available (but in active dev) here .

+7
javascript jquery html forms formcollection
source share
2 answers

I assume that you have a reference to the .collection object that you want to find in the add buttons for a variable named target . If so, you can do it like this:

 target.find(".add").filter(function(i, element) { return $(element).closest(".collection").get(0) === target.get(0); }); 

This finds all .add buttons that are in the given .collection , and then removes all that are contained in the nested .collection , and not directly in the target .collection .

+5
source share

Try

 $(".add").not($(".collection:gt(0) .add")); 

Note

Using jQuery . not () .not( selector ) , where selector is the selctor string

. not (selector) version added: 1.0

Selector Type: Selector or Element or Array A string containing a selector expression, a DOM element, or an array of elements to match against a set.

$(".add").not(".collection:gt(0) .add") http://jsfiddle.net/47wc5L96/21/

didn't return to the same results as .not( selection ) , where selection is a jQuery object

. not (selection) version added: 1.4

selection Type: jQuery existing jQuery object to match the current set of elements.

$(".add").not($(".collection:gt(0) .add")); http://jsfiddle.net/47wc5L96/20/


 console.log($(".add").not($(".collection:gt(0) .add"))); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <div class="collection"> <div>something</div> <div>something</div> <div> <div class="add">+</div> </div> <div>something</div> <div class="collection"> <div>something</div> <div>something</div> <div> <div class="add">+</div> </div> <div>something</div> </div> </div> 
+3
source share

All Articles