ninjascorner
ninjascorner

Reputation: 299

Programmatically apply the image alt attribue as a class to parent element

I want to add as a class the image alt attribute to its container element. Markup:

<div class="field-group-our-people">
  <div class="field-items even>
   <img alt="John">
  </div>
  <div class="field-items odd>
   <img alt="Kevin">
  </div>
  <div class="field-items even>
   <img alt="Kate">
  </div>
  <div class="field-items odd>
   <img alt="Martin">
  </div>
</div>

To be like this:

<div class="field-group-our-people">
      <div class="field-items even john>
       <img alt="John">
      </div>
      <div class="field-items odd kevin>
       <img alt="Kevin">
      </div>
      <div class="field-items even kate>
       <img alt="Kate">
      </div>
      <div class="field-items odd martin>
       <img alt="Martin">
      </div>
</div>

My Jquery code(but not working):

//Add the image alt attribute as class for individual styling
$('.group_our_people .field-item').each(function() {
  var att = $('.group_our_people .field-item img').attr('alt');               
  $(this).addClass(att);        
});

What is wrong/missing in my code?

Upvotes: 1

Views: 280

Answers (3)

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29166

$('div.field-group_our_people div[class^=".field-items"] img').each(function()
{
  var att = $(this).attr('alt');               
  $(this).parent().addClass(att);        
});

Upvotes: 1

Nadh
Nadh

Reputation: 7253

$('.field-group-our-people .field-items img').each(function() {
     $(this).parent().addClass( $(this).attr('alt') );
});

Upvotes: 1

mgibsonbr
mgibsonbr

Reputation: 22007

You should get the img that is child of the current div (on iteration):

var att = $(this).find('img').attr('alt');

The way you're doing (i.e. repeating the selector), you end up retrieving multiple values, and only the first one is taken into account. So, every div will get its class: "John".

Upvotes: 2

Related Questions