0
<div id="item">
    <div class="action">
        Oh! Look, a squashed pea!
    </div>
    <img class="picture" src="example">
</div>

Using jQuery, when hovering over the image I need to the the DIV with the class name 'action'. The hovering part I have down-pat and works fine, but I'm struggling with the selector part.

I've tried selecting the parent, then sibling with 'action' class with no luck...

EDIT: more info I should have added but clumsily didn't trying to make it easier to read - my bad.

<div id="item"> 
    <div class="action"> 
        <span>Oh! Look, a squashed pea!</span>
        <button id="add">Hello</button>
    </div> 
    <img class="picture" src="example"> 
</div> 

I'm still after a reference to the DIV with the .action class applied WITHOUT referencing any ID's.

Alex Guerin
  • 2,336
  • 10
  • 36
  • 53
  • `.action` is not a sibling of the parent of the image, that would never work. In general, have a look at the jQuery documentation: http://api.jquery.com/category/traversing/ – Felix Kling Feb 26 '12 at 23:35
  • possible duplicate of [How do I select a sibling element using jQuery?](http://stackoverflow.com/questions/7463242/how-do-i-select-a-sibling-element-using-jquery) – Felix Kling Feb 26 '12 at 23:37

2 Answers2

0

You could use .prev() to get the previous sibling. Within your hover-function it would be:

$(this).prev();
Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
0
$("#item img")
    .on("mouseover", function(){
    var prevAction = $(this).prev();
    prevAction
        .css("background-color","red");
});

We use prev() to select the immediately preceding element. (We then proceed to set its background color to red, but that's the part you change). In this case, the element you want to select is stored in the variable prevAction.

EDIT: For your update:

$("img.picture")
    .on("mouseover", function(){
    var prevAction = $(this).prev();
    prevAction
        .css("background-color","red");
});

Instead of selecting an image within the div with the id item, we select the image with the class picture. This may conflict with other elements if you have images with the same class outside of those #item divs. In which case, you could probably make the selector more specific:

$("div img.picture")

This will select images with the class picture inside any div element (regardless of id or class).

Purag
  • 16,941
  • 4
  • 54
  • 75