alyus
alyus

Reputation: 1007

Add a class to a parent element based on image alt tag?

Check a few of the other post and found the code I needed, but doesn't do exactly what I need it to do.

I want to add a class to the parent element based on the alt tag of an image.

So from this:

<div class="img-wrap">
   <div class="img-icon">
      <a href="">
         <img alt="home" />
      </a>
   </div>
</div>

To this:

<div class="img-wrap home">
   <div class="img-icon">
      <a href="">
         <img alt="home" />
      </a>
   </div>
</div>

Here's the code I'm using:

$('img').each(function() {
$(this).parent().addClass( $(this).attr('alt') );
});

While this adds the needed class, it adds it to the "a"... however I want it to add to the #img-wrap. How can I do this?

Upvotes: 1

Views: 917

Answers (4)

Sushanth --
Sushanth --

Reputation: 55750

Try using .closest()

Note that Id in the HTML page is supposed to be unique.. Try giving the div a class instead of an ID

    $('img').each(function() {
       $(this).closest('.img-wrap').addClass( $(this).attr('alt') );
    });


<div class="img-wrap">
  <div class="img-icon">
     <a href="">
       <img alt="home" />
     </a>
  </div>

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79850

ID should be unique.. You should not duplicate ID like that. Try changing it to class class="img-wrap" and check out the below code.

HTML:

<div class="img-wrap">
   <div class="img-icon">
      <a href="">
         <img alt="home" />
      </a>
   </div>
</div>

Code:

$('img').each(function () {
   $(this).closest('.img-wrap').addClass(this.alt);
});

Upvotes: 3

adamb
adamb

Reputation: 4883

use .closest() to select the parent element you want http://api.jquery.com/closest/

Upvotes: 0

kalpaitch
kalpaitch

Reputation: 5271

$('img').each(function() {
$(this).parents('#img-wrap').addClass( $(this).attr('alt') );
});

OR

$('img').each(function() {
    $(this).parent().parent().parent().addClass( $(this).attr('alt') );
    });
//to make it more obvious why it is not selecting the #img-wrap <div>

And yes, #IDs should only be used once, use a class instead if this repeats itself

Upvotes: 1

Related Questions