Martin Los
Martin Los

Reputation: 3

Change css depending on parent class

I need help with the following problem. I need to change css property (background) to something depending on the class name of the parent. This is my code.

HTML

<div id="types">
  <ul>
    <li class='car'><a href='#'>Car</a></li>
    <li class='bus'><a href='#'>Bus</a></li>
  </ul>
</div>

I need to change background-image of the a tags. If I'm in li.car, then background will be images/car.png, and if in the li.bus, then images/bus.png.

I can't figure out where is the problem. This is how I started, and this works.

$('#types ul li a').css('background', "url('./images/skills/cooking.png') 
   center center no-repeat");

But when I change it to something like that, it won't work:

$('#types ul li a').css('background', 
   "url('./images/skills/'+($(this).parent().attr('class'))+'.png') 
   center center no-repeat");

What is wrong?

Upvotes: 0

Views: 171

Answers (1)

AdrianCooney
AdrianCooney

Reputation: 703

Code inside quotes won't get executed unless you specifically invoke it eval or the Function constructor. Try bumping it outside the quotes and it should work.

$('#types ul li a').each(function() {
        $(this).css('background', "url('./images/skills/" + ($(this).parent().attr('class')) + ".png') center center no-repeat");
    });

Upvotes: 1

Related Questions