Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone a filtered jQuery object?

I load a XML document to jQuery using $xml = $(xmldoc). Then I filter it via $xml.filter('id="something"'). When using .index() on the filtered xml, jQuery returns the index in the original listing, not in the filtered listing.

Example:

<xmlroot>
  <xmlnode id="1" color="blue" />
  <xmlnode id="2" color="orange" />
  <xmlnode id="3" color="blue" />
  <xmlnode id="4" color="orange" />
  <xmlnode id="5" color="blue" />
</xmlroot>

    vObject = $xml.filter('[color="orange"]'); //vObject should just receive the xmlnodes 2 and 4
    vResult = vObject.filter('[id="4"]').index();

vResult will always be 3, but it should be 1.

I know this jQuery behaviour is by design, but I need a solution to fill vObject with the filtered xml, not with all of the xml. I've tried all night and I'm out of ideas.

Would be very glad if one of the experts here could help. Thanks!

like image 513
The Conspiracy Avatar asked Feb 04 '26 03:02

The Conspiracy


1 Answers

If you want to get the index of an element within jQuery collection you should pass the element to the index method:

var vResult = vObject.index(vObject.filter('[id="4"]')); // 1    
           // vObject.index(vObject.filter('[id="2"]')); // 0
           // vObject.index(vObject.filter('[id="3"]')); // -1

http://jsfiddle.net/C9Nyg/

like image 148
undefined Avatar answered Feb 06 '26 17:02

undefined



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!