Search code examples
jquerydomselectorparent

jQuery select only children until specific class


I have some recursive HTML in the following tree structure:

div.item
 div.content
  input
  div.container
   div.item
    div.content
     input
     div.container
      div.item
       etc...

Here's a jsfiddle with a working example: http://jsfiddle.net/HWHRZ/

I also have a objects with jQuery references to each of the .item divs.

What I want to do is, for any specific .item, select only the inputs immediately underneath, excluding those in any deeper .container or .item elements.

To make things more complicated, not every .item has an identical layout with regards to the inputs. Sometimes inputs may be in other div elements, so selecting them with a simple .find('> .content :input') won't always work.

I have found a solution, but it's inefficient with large trees and not at all elegant: $(':input', $item).not($('.container :input', $item)).toggleClass('changed'); ($item is a reference I keep in an object). This solution works as it should, but is way too inefficient for any sufficiently large tree structure, is the not() would have to process a lot of node.

In short: I need to select specific child nodes that are NOT within specific other child nodes.

Does anybody know of a more efficient way of doing this?


Solution

  • I think

    $.each($($(".item")[0]).children(".changed"),function(){
    $(this).removeClass("changed")
    })
    

    should work.