proseidon
proseidon

Reputation: 2305

Selecting an element that has a specific child?

If I wanted to do a CSS selector on a list like this:

<ul>
    <li></li>
    <li><a></a></li>
    <li><a></a></li>
    <li><a></a></li>
</ul>

and I wanted to do a li:hover effect on only the lis that contain an <a> tag, is there a way to specify that in CSS? if li:hover contains <a> then li:hover effect = X?

Upvotes: 6

Views: 9275

Answers (4)

Jozsef Kerekes
Jozsef Kerekes

Reputation: 218

For that you need a CSS4 parent selector, but of course it's not supported for now.

$li:hover a { ... }

If it doesn't matter what tag is inside, you could just use:

li:hover {border:1px solid red}
li:empty:hover {border:0}

:empty selector is not supported in ie7.

http://jsfiddle.net/aD6Ws/

Jquery alternative is :

$("li:has('a')").hover(function() { ... },function(){ ...  })

Upvotes: 0

Ali Bassam
Ali Bassam

Reputation: 9959

You can do it in JQUERY:

$("a").parent("li").css("color","#923123");

For what you requested, it would be like this:

$("li").mouseover(function(){

   if ($(this).is(':parent'))
   {
       //this <li> has a child, supposed to be <a>
   }

});

Upvotes: 1

Mark
Mark

Reputation: 3035

Depending on your ultimate objective and what the effect is, you could apply the styles to the anchor tag - which then wouldn't apply to those list items without one.

Alternatively, whilst you can't do this directly in CSS, if the list is dynamic and you can identify the list items that contain a link at the point of generation, you could apply classes based on their status and style accordingly.

If it's not a dynamic list, just add the classes manually.

Upvotes: 0

Jon
Jon

Reputation: 437336

No, CSS does not allow you to select elements based on their descendants.

Upvotes: 5

Related Questions