开发者

Format li which contain links different from li which contains no links

i have list like that:

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

where both type of listelements are there multiple times in arbitrary order. Is there a way to format those li's differently? (different list-style-image) The only difference 开发者_StackOverflow社区is that the one kind contains a link and the other one doesnt.


No, there is no way in CSS to specify a selector depending on the child elements.

You would have to add something to distinguish the li elements themselves, like a class on all li elements that contains links.

If you can use jQUery, you could add the class to the li elements that contains anchor tags:

$('li:has(a)').addClass('linkItem');

A non-jQuery solution could look like this:

var items = document.getElementsByTagName('LI');
for (var i=0; i<items.length; i++) {
  if (items[i].getElementsByTagName('A').length > 0) {
    items[i].className = 'linkItem';
  }
}


sure. If you give each different li a class you can do it simple. Or you can always do this if you can't use classes.

ul li
{
    styles....
}
ul li a 
{ 
    styles.... 
}

The styles in the first class will apply to all li elements and styles in the second class will apply to the < a > tags respectively.


You can't do this with CSS alone, you could use Javascript to accomplish this. Here's an example using jQuery:

$('ul li a').each(function() {
  $(this).parent().css('list-style-image', 'url("/path/image.gif")');
});

This will set the style for the li tags, not the a tags. Technically, the list-style-image property is supposed to be set for ul tags, not li, but most (all?) browsers handle it the way you would expect when you style the li tags individually.


Hello there

I would add a <p></p> tag like this:

<ul>
 <li><a...>...</a></li>
 <li><p></p></li>
</ul>

And then apply 2 different styles like this:

ul a {display:block; padding:3em; background: #ccc;}
ul p {display:block; padding:3em; background: #aaa;}

I would not recommend using javascript for this, some people block javascript ect. but it depends. I would perfer css/html.

Edit: For some reason you can write <p></p> without making it code - Fixed

Also I might have overlooked that you wanted to apply list-style-image, then this will not work.


This is what classes are for. In HTML:

<ul>
 <li class="linked"><a...>...</a></li>
 <li>...</li>
</ul>

and in CSS

ul li {...}
ul li.linked {...}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜