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

html, jquery, jquery-selectors

Solution

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))')

Problem

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 me </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.

Original source