开发者

jQuery to select where no children or first child is not image

I'm trying to dynamically style some elements on my pages. So, if I had the following code:

<a href="#">
  Select Me
</a>

<a href="#">
  <img src="blah.jpg" />
  Don't select m开发者_开发知识库e
</a>

<a href="#">
 <div>Don't select me either</div>
 <img src="blah.jpg" />
</a>

<a href="#">
  <div>You can select me too.</div>
</a>

I would like it to select the first and fourth tags.

From what I could tell, by using:

 $("a:first-child")

Won't select the first tag because it doesn't have any children (just text). The second tag should not get selected so something like:

$("a:first-child").not("img)

but that leaves out the first item.

EDIT: If there is an IMG anywhere in the A element, don't select it.


If you want to select all links which don't have an image as the first child, use this:

$('a:not(:has(> img:first-child))')

If you want to select all links which don't have an image at all, use this:

$('a:not(:has(img))')


Assuming I've understood your question properly,

$("a:not(:has(img))");

http://api.jquery.com/not-selector/
http://api.jquery.com/has-selector/


After your comments below, the selector I wrote originally should work for you.


I have not tried it, but you should write something like this:

$("a").filter(function() {
    return $(this).filter("> img:first-child").length != 0;
})

It will first select all the a's and then filter the ones that have an img as first child.

UPDATE:
nickf solution is definitely clearer :-)
I often forget how versatile the jquery selector is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜