I’m trying to select 2 of 3 existing a elements from a repeating HTML structure and having trouble designing an efficient jquery selector.
Here is the markup. I’m trying to select Link 1, Link 2, but not Link 3. Note that the entire HTML structure (div.container) could occur multiple times. If it does, I need Link 1 and Link 2 from all container classes.
NOTE 1: I cannot modify the markup.
NOTE 2: I’d prefer the solution be completely selector based (and avoid calls to .find(), etc., as this selector has to be combined with another selector 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>
When a single container structure occurs, a simple selector is:
$(".container a:lt(2)");
However if multiple container structures exist, the above only selects Link 1 and Link 2 from the first container.
The below works for one or more container structures, but I don’t like it. It seems inefficient to setup multiple css path selectors.
$(".container h1 a, .container .left a");
In verbose language, I would like to “select all a tags within class container not contained within class right. Is this possible? Or is the above selector using 2 CSS paths the best option.
Try like below,
DEMO
Alternatively as a workaround you can try like below if you want it in 1 line.. Note that this only will work for the presented markup. Any markup change will break the code.
DEMO