mystery
mystery

Reputation: 19513

Is there a way to select element(s) by the elements they contain?

I have several divs, and I want to select them if they contain an a element, e.g.:

<div><a href="http://example.com">link</a></div>
<div>No link</div>

I want to select the div with the link in it, but not the one without. Is this possible without javascript?

Also, the reason I want this is for a subreddit stylesheet, therefore I can't adjust the actual HTML, only the CSS.

Upvotes: 1

Views: 153

Answers (4)

Caleb Irie
Caleb Irie

Reputation: 358

How about $('div > a').parent().whateveryouneedtodo()?

Upvotes: -1

Jawad
Jawad

Reputation: 6672

You could use the :nth-child(N) selector based on the position of the div elements inside the parent element, whatever that may be. So in you above example, the div element that has the a element inside it, is the first child and the other div element which does not have the a element is the second child. It is not clear from you code that if these div elements are children of any other elements or are they the children of the body element. In case they are the children of the body element you could do as

div:nth-child(1)

This will select the first div

div:nth-child(2)

This will select the second div.

Offcourse you have to figureout for yourself which nth-child has any other elements nested inside it and than use that position for the value of "N". If you div elements has nothing inside it, you could use

div:empty

Upvotes: 1

faq
faq

Reputation: 3076

first you have to name the link and the div 'class' and 'id' like so: and the css will look like this :

#divname,a.linkname {property:value;}

hope it is a good answer

Upvotes: -2

Jason McCreary
Jason McCreary

Reputation: 73001

You're trying to apply styles to the ancestor based on the descendant. This is not possible in CSS.

The closest thing is the direct child selector. But this would apply styles to a within a div, not the other way around.

div > a

Read more about CSS Selectors. I'd suggest looking for another way to select these elements or applying your styles to the a with the above.

Upvotes: 3

Related Questions