Search code examples
javascriptjqueryhtmlformsformcollection

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


I am building a jQuery plugin to manage form collections. The plugin aims to add add, remove, move up and move down buttons to alter that collection.

  • A collection's root node always contains a selector, such as .collection.

  • A button can be anything as soon as it has the .add class

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

To simplify the problem, look at 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 the button can be arbitrary deep: collection is built by an user and I don't know where can be the button in the dom. BTW, it is deeper than the .collection, that's all I know.

How to select all add buttons until the second .collection, but not further?

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


Solution

  • I will assume you have a reference to the .collection object that you want to find the add buttons for in a variable called 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 the .add buttons that are in a given .collection and then removes any who are contained in a nested .collection instead of directly in the target .collection.