开发者

Need help constructing a jQuery query

开发者 https://www.devze.com 2023-03-25 11:37 出处:网络
I\'m having issues with a jQuery query. Consider the following (crazy) HTML example: <!-- this is the outermost condition -->

I'm having issues with a jQuery query.

Consider the following (crazy) HTML example:

<!-- this is the outermost condition -->
<div id="condition">

     <!-- this is a tag that I am looking for -->
     <input type="text" />

     <div id="condition">
          <inp开发者_StackOverflow社区ut type="radio" />
     </div>

     <div>

          <div id="condition">
               <input type="checkbox" />
          </div>

          <!-- this is a tag that I am looking for -->
          <input type="text" />

     </div>
</div>

Given the above example-markup and the outer-most condition (seen in the top), how can I get all input elements WITHIN that condition, that are not members of inner conditions as well?

I've provided examples so you can see which tags I want the query to return.


All html elements on a page should have a unique ID.

That said, you could do something like this:

// select the :first #condition
var $first = $("#condition:first");

// use map() to filter out inputs that don't meet our criteria
// and dump them into the inputs Array.
var inputs = $first.find("input").map(function() {

    // select parent with #condition ID
    var $parent = $(this).parent("#condition");

    // if parent == null or parent doesn't have any parents with ID = #condition
    // return the input, otherwise null, which removes it from the list
    return $parent.length == 0 || $parent.parents("#condition").length == 0 
        ? $(this) : null;
});

You end up with is an Array of inputs that are not wrapped in #condition or its parent is the first #condition element


working example: http://jsfiddle.net/hunter/EsYLx/


Well first off you can't have 2 elements with the same ID - they must be unique, but if you went ahead and changed them to classes you could use something like:

$('#condition input:not(#condition #condition input)').doSomething();


This should work: Note you have 2 ids and ids should be unique.

$("#condition > input").html();


You can do this:

var found = $('#condition input').filter(function() {
    var parents = $(this).parents('.condition');
    return parents.length === 1 && parents[0].id === 'condition';
});

However, you're HTML is not only crazy, it's invalid. You can't have multiple elements with the same ID, so you need to fix that first.

Here's a working example: http://jsfiddle.net/FishBasketGordo/R7MX4/

0

精彩评论

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