Search code examples
jquerydomtraversal

jquery find preceding sibling


I am wanting with jquery to find the preceding sibling of an element, so for a example,

<li>
    <a href="">
        <img src="http://placehold.it/45x45" alt="Profile Image"/>
        <hgroup>
            <h5>Person Number 1</h5>
            <h6>Recruitment Consultant</h6>
        </hgroup>
     </a>
</li>
<li>
    <a href="">
        <img src="http://placehold.it/45x45" alt="Profile Image"/>
        <hgroup>
            <h5>Person Number 2</h5>
            <h6>Recruitment Consultant</h6>
        </hgroup>
     </a>
</li>
<li>
    <a href="">
        <img src="http://placehold.it/45x45" alt="Profile Image"/>
        <hgroup>
            <h5>Person Number 3</h5>
            <h6>Recruitment Consultant</h6>
        </hgroup>
     </a>
</li>

If I were to hover of the second list element a how would I find the previous li's a?

My attempt is below,

$('resultsset a').hover(function(){
    $(this).prev().find('li a').css('bottom-bottom', '1px solid #000');
},
function() {
    $(this).prev().find('li a').css('bottom-border', '1px solid #c0c0c0');
});

Solution

  • You're close. You want to find the element's parent's previous sibling and then find the a within that.

    $(this).parent().prev().find('a')