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?
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?
5 Answers
Reset to default 5You 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>
You can't make an optional element selector (other than using *
but that's not a great idea). Instead you could bine 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.
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);
Use only
$('div.myClass span img').css('opacity', 0.5);
It will work as your requirements.
You could also cut the expression, and use find
$('div.myClass span').find('a>img, img').css('opacity', 0.5);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745546041a4632342.html
评论列表(0条)