user2226032
user2226032

Reputation: 65

Identify a specific class element within another div

I have a series of photos on a page, which have below them some text information and some buttons:

<div class="photowrapper">
 <div class="photowrapperphoto">
  <div class="photocontainer">image</div>
  </div>
 <div class="textwrapperphoto">
  <div class="textleftwrapperphoto">
   <div class="phototitle">photo_0001</div>
   <div class="photoprice">&pound;3.00</div>
   <div class="photosize">6 by 4 inch</div>
 </div>
 <div class="textrightwrapperphoto">
  <div class="photoaddbutton">Add</div>
  <div class="photoremovebutton">Delete</div>
 </div>
</div>

I want to put in some jquery so that when someone clicks on the 'photoaddbutton', it amends the class of 'photowrapperphoto' (to add a background color).

I can't seem to figure out how to identify the element photowrapperphoto.

I have loads of the above html (i.e. loads of images) on the page. I just want the immediately preceeding 'photowrapperphoto' to change, but at the moment the jquery I'm using changes all 'photowrapperphoto' classes on the page.

$(document).ready(function() {
 $('.photoaddbutton').click(function() {
  $('.photowrapperphoto').attr('class', 'photowrapperphotoselected');
 });
});

Any ideas?

Upvotes: 1

Views: 297

Answers (2)

tcovo
tcovo

Reputation: 7740

I'd recommend you let the photowrapperphoto items keep their photowrapperphoto class, and add an additional class selected, instead of changing the class.

The javascript to modify the correct photowrapperphoto could be:

$(document).ready(function() {
    $('.photoaddbutton').click(function() {
        $(this)
            .closest('.photowrapper')   // go up in the DOM until .photowrapper
            .children('.photowrapperphoto') // go down one level to .photowrapperphoto 
            .addClass('selected');
    });
});

To specify a special style for the selected photowrapperphoto, you can use a rule like this in your CSS:

.photowrapperphoto.selected
{
    background-color: red;
}

Upvotes: 1

Walter Tross
Walter Tross

Reputation: 12624

$(document).ready(function() {
   $('.photoaddbutton').click(function() {
      $(this).closest('.photowrapper').find('.photowrapperphoto').prop('class', 'photowrapperphotoselected');
   });
});

But I recommend adding and removing a class, not replacing one by the other. The first class marks the generic role of the element, the second one marks it's additional role when present.

Upvotes: 0

Related Questions