Selecting an element with a specific child?

If I wanted to make a CSS selector on a list like:

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

      

and I would like to make an effect li:hover

only for li

that contains the tag <a>

, is there a way to specify this in CSS?if li:hover contains <a> then li:hover effect = X?

+3
css


source to share


4 answers


No, CSS doesn't allow you to select elements based on their descendants.



+5


source to share


You can do this in JQUERY:

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

      



For what you requested, it will look like this:

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

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

});

      

+1


source to share


Depending on your end goal and what the effect is, you can apply styles to the anchor tag - which then won't be applied to those list items without one.

Alternatively, although you cannot do this directly in CSS, if the list is dynamic and you can identify the list items containing a link at the point of generation, you can apply classes appropriately based on their status and style.

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

0


source to share


You need a CSS4 parent selector to do this, but of course it's not supported yet.

$li:hover a { ... }

      

If it doesn't matter which tag is inside, you can simply 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:

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

      

0


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics