Reputation: 15660
I'm trying to select an element through jQuery, but one of the element in the selection is optional. So I have something like this:
$('div.myClass span a>img')
In my scenario, that a
element is an optional one. It may or may not exist in the DOM.
Of course, I can write out the entire line again with one containing a
but this looks verbose:
$('div.myClass span a>img').css('opacity', 0.5);
$('div.myClass span img').css('opacity', 0.5);
Is it possible to define the a
element to be optional in the jQuery selector path?
Upvotes: 1
Views: 1100
Reputation: 21890
You only need the a >
if you want to specifically target only images within the anchor. Otherwise, div.myClass span img
will target any image inside the span.... regardless of the presence of an anchor tag.
$('div.myClass span a > img');
<div class="myClass">
<span>
<a href="#"><img src="THIS IMAGE IS TARGETED" /></a>
<img src="BUT THIS IMAGE IS NOT" />
</span>
</div>
$('div.myClass span img');
<div class="myClass">
<span>
<a href="#"><img src="THIS IMAGE IS TARGETED" /></a>
<img src="THIS IMAGE IS ALSO TARGETED" />
</span>
</div>
$('div.myClass span img').not('a > img');
<div class="myClass">
<span>
<a href="#"><img src="THIS IMAGE IS ** NOT ** TARGETED" /></a>
<img src="THIS IMAGE IS TARGETED" />
</span>
</div>
Upvotes: 5
Reputation: 1296
You could also cut the expression, and use find
$('div.myClass span').find('a>img, img').css('opacity', 0.5);
Upvotes: 0
Reputation: 944
Use only
$('div.myClass span img').css('opacity', 0.5);
It will work as your requirements.
Upvotes: 0
Reputation: 725
You can use a context and make your selectors behind it like:
$('a > img, img', 'div.myClass span').css('opacity', 0.5);
And in your case, you only need the img
because a > img
will select the same image:
$('img', 'div.myClass span').css('opacity', 0.5);
Upvotes: 1
Reputation: 337656
You can't make an optional element selector (other than using *
but that's not a great idea). Instead you could combine both the selectors in to a single jQuery object, like this:
$('div.myClass span a>img, div.myClass span img').css('opacity', 0.5);
Note however that if the second selector is valid for your scenario, then the >
selector is redundant anyway.
Upvotes: 4