Forums

[resolved] How to add class to last list item (4 posts)

  1. steverydz
    Member
    Posted 1 month ago #

    Hi, I have an unordered list and each list item is floated left and has a right margin of 20px.

    This list has to be the exact width of the screen so I need to dynamically add a class of last to the last list item. I can do this with :last-child in modern browsers however this doesn't work in IE.

    Does anyone know of a way I can dynamically add a class of .last to the final item in Wordpress?

  2. steverydz
    Member
    Posted 1 month ago #

    Not to worry. I've figured out that IE7 and 8 support :first-child but not :last-child so I can use that instead.

  3. slamstar
    Member
    Posted 1 month ago #

    Did you find the solution?

  4. stakabo
    Member
    Posted 3 weeks ago #

    hey,

    i had the same probleme, then i found a function in a thread, but it did not work, so i rewrote it and is works pretty well,

    i'm shure it could be imporved by comdining both regex into one, but still, it works pretty good

    it will ad a first and a last class to the li

    function add_last_class($input) {
    	if( !empty($input) ) {
    
    		$pattern = '/<li class="/is';
    		$replacement = '<li class="first ';
    
    		$input = preg_replace($pattern, $replacement, $input);
    
    		$pattern = '/<li class="(?!.*<li class=")/is';
    		$replacement = '<li class="last ';
    
    		$input = preg_replace($pattern, $replacement, $input);
    
    		echo $input;
    	}
    }
    
    /* the echo=0 parma is important here */
    add_last_class(wp_list_categories('title_li=&echo=0'));

    hope it helps

Reply

You must log in to post.

About this Topic