0

I have a category color function in functions.php file and I am assigning category color for every li element with this code:

$i = 0;
$color = get_term_meta( $menu_item->object_id, '_category_color', true );
$color = ( ! empty( $color ) ) ? "#{$color}" : '#fff';
$menu_list .= "\t\t\t\t\t". '<li id="'.$i .'"style="border-left:5px solid '.$color .';">
<a href="'. $url .'">'. $title .'</a></li>' ."\n";
$i++;

And I am trying to get every li's border-left-color and assign them as a background to that div but in this jquery code, $i is stopping in 1 . How can I make this as a loop for every li?

$(document).ready(function(){
$i = 0;
var $c=$('.side-category ul li#'+$i).css("border-left-color");
$('.side-category ul li#'+$i).css("background", $c);
$i++;
});

Thank you for reading it!

4
  • 2
    You don't have any loop... Commented Jun 14, 2017 at 16:36
  • Yes, I am not good at jquery, and I couldnt make a loop :)How can I make this as a loop ? Commented Jun 14, 2017 at 16:38
  • You can't define the background color on the server because...? Commented Jun 14, 2017 at 16:40
  • jQuery Learning Center Commented Jun 14, 2017 at 16:40

1 Answer 1

3

Replace the code within document.ready with this :

$('.side-category ul li').each(function(){
    $(this).css("background", $(this).css("border-left-color"));
})

There is no need to add $i , jQuery has each function , so you can directly use that.

The each function will go through each li within .side-category ul

Sign up to request clarification or add additional context in comments.

3 Comments

By the way, Is there a option to apply background-color when :hover to li element?
Yes , you have to bind that event with each li.Post a different question for that , I post the answer over there :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.