Having difficulty creating an efficient jQuery selector to choose 2 out of 3 existing a
elements within a repeating HTML structure.
Below is the code snippet. The goal is to select Link 1
, Link 2
, excluding Link 3
. Keep in mind that the entire HTML structure (div.container
) may appear multiple times, and I need Link 1 and Link 2 from all instances of the container
class.
NOTE 1: Markup cannot be altered.
NOTE 2: Preferring a solution entirely based on selectors (avoiding calls to .find()
, etc., as this selector will be combined with another one outside the scope of this question).
<div class="container">
<h1>
<a href="http://www.google.ca">Link 1</a>
</h1>
<div>
<div class="left">
<p>
<a href="http://www.google.ca">Link 2</a>
</p>
</div>
<div class="right">
<a href="http://www.google.ca">Link 3</a>
</div>
</div>
</div>
A simple selector for a single container
structure would be:
$(".container a:lt(2)");
However, if there are multiple container
structures, the previous method only selects Link 1 and Link 2 from the initial container.
The following approach works for one or more container
structures, but it's not ideal. Setting up various CSS path selectors seems inefficient.
$(".container h1 a, .container .left a");
In simpler terms, I want to "select all a
tags within the container
class that are not located within the right
class." Is there a way to achieve this? Or should I stick with the two-CSS-path selector mentioned earlier?