Comparing two large sets of attributes
- by andyashton
Suppose you have a Django view that has two functions:
The first function renders some XML using a XSLT stylesheet and produces a div with 1000 subelements like this:
<div id="myText">
<p id="p1"><a class="note-p1" href="#" style="display:none" target="bot">?</a></strong>Lorem ipsum</p>
<p id="p2"><a class="note-p2" href="#" style="display:none" target="bot">?</a></strong>Foo bar</p>
<p id="p3"><a class="note-p3" href="#" style="display:none" target="bot">?</a></strong>Chocolate peanut butter</p>
(etc for 1000 lines)
<p id="p1000"><a class="note-p1000" href="#" style="display:none" target="bot">?</a></strong>Go Yankees!</p>
</div>
The second function renders another XML document using another stylesheet to produce a div like this:
<div id="myNotes">
<p id="n1"><cite class="note-p1"><sup>1</sup><span>Trololo</span></cite></p>
<p id="n2"><cite class="note-p1"><sup>2</sup><span>Trololo</span></cite></p>
<p id="n3"><cite class="note-p2"><sup>3</sup><span>lololo</span></cite></p>
(etc for n lines)
<p id="n"><cite class="note-p885"><sup>n</sup><span>lololo</span></cite></p>
</div>
I need to see which elements in #myText have classes that match elements in #myNotes, and display them. I can do this using the following jQuery:
$('#myText').find('a').each(function() {
var $anchor = $(this);
$('#myNotes').find('cite').each(function() {
if($(this).attr('class') == $anchor.attr('class')) {
$anchor.show();
});
});
However this is incredibly slow and inefficient for a large number of comparisons.
What is the fastest/most efficient way to do this - is there a jQuery/js method that is reasonable for a large number of items? Or do I need to reengineer the Django code to do the work before passing it to the template?