Note that there are some explanatory texts on larger screens.

plurals
  1. POPrototypeJS: Selecting the odd subset of visible children
    primarykey
    data
    text
    <p>This is related to my <a href="https://stackoverflow.com/questions/796273/prototypejs-selecting-visible-elements">previous question about selecting visible elements</a>. Now, here's the twist: Let's say I want to select the odd children only from the set of visible children of an element. What would be the best way to do this?</p> <p>Edit: here is an example of my input and expected output.</p> <pre><code>&lt;!-- A list with some visible and invisible children --&gt; &lt;ul class="stripe"&gt; &lt;li&gt;Visible 1&lt;/li&gt; &lt;li style="display:none;"&gt;Visible 2&lt;/li&gt; &lt;li style="display:none;"&gt;Visible 3&lt;/li&gt; &lt;li&gt;Visible 4&lt;/li&gt; &lt;li style="display:none;"&gt;Visible 5&lt;/li&gt; &lt;li&gt;Visible 6&lt;/li&gt; &lt;li&gt;Visible 7&lt;/li&gt; &lt;/ul&gt; &lt;!-- Only the visible children. --&gt; &lt;li&gt;Visible 1&lt;/li&gt; &lt;li&gt;Visible 4&lt;/li&gt; &lt;li&gt;Visible 6&lt;/li&gt; &lt;li&gt;Visible 7&lt;/li&gt; &lt;!-- The "odd" visible children. --&gt; &lt;li&gt;Visible 1&lt;/li&gt; &lt;li&gt;Visible 6&lt;/li&gt; </code></pre> <p>I came up with two ways. One works, but the other doesn't.</p> <pre><code>// Method one: Returns the odd children whether they are visible or not. :( var listChildren = $$("ul.stripe &gt; li"); var oddChildren = allChildren .findAll(function(el) { return el.visible(); }) .findAll(function(el) { return el.match("li:nth-child(odd)"); }); oddChildren.invoke("addClassName", "odd"); </code></pre> <p>What I am currently doing now is the following:</p> <pre><code>// Method two: grouping! var listChildren = $$("ul.stripe &gt; li"); var oddChildren = listChildren .findAll(function(el) { return el.visible(); }) .eachSlice(2, function(el) { el[0].addClassName("odd"); }); </code></pre> <p>This code seems like it could be improved. Can anyone suggest a better way to accomplish this?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload