Search code examples
javascriptjqueryhtmlsiblingsclosest

jQuery get sibling or closest element not working


I just can't get this tiny piece of code to work. I'm basically trying to get the sibling of the clicked ahref, but It just returns the clicked element itself (used console.log() to test this).

$('.script-vote').click(function(e) {
    e.preventDefault();
    var href = $(this);

    href.siblings('.script-vote') //This doesn't work
        .removeClass('active');

    href.closest('.script-vote') //This doesn't work
        .removeClass('active');
});

And my HTML:

<div class="one-half t-center">
    <a href="..." class="script-vote up" title="Upvoten">
        <i class="fa fa-thumbs-o-up"></i>
        <span class="score"><?=$post->getUpVotes()?></span>
    </a>
</div>
<div class="one-half t-center">
    <a href="..." class="script-vote down" title="Downvoten">
        <i class="fa fa-thumbs-o-down"></i>
        <span class="score"><?=$post->getUpVotes()?></span>
    </a>
</div>

So when I click click the .script-vote.up element, I want to remove the active class of .script-vote.down. Thanks in advance.


Solution

  • The <a> elements in your HTML do not have any siblings. But their parents do. Make sure that they are enclosed in a grand-parent div:

    <div class="voting-container">
    <div class="one-half t-center">
        <a href="..." class="script-vote up" title="Upvoten">
           <i class="fa fa-thumbs-o-up"></i>
            <span class="score"><?=$post->getUpVotes()?></span>
        </a>
    </div>
    <div class="one-half t-center">
        <a href="..." class="script-vote down" title="Downvoten">
            <i class="fa fa-thumbs-o-down"></i>
            <span class="score"><?=$post->getUpVotes()?></span>
        </a>
    </div>
    </div>
    

    You can refer to the following JavaScript with jQuery as an example:

    $(".script-vote").click(function(){
    
        var otherVotingButton = $(this).parent().siblings(".one-half").first().find(".script-vote");
    
        otherVotingButton.css("background-color","red");     
    
        otherVotingButton.href="#";
        otherVotingButton
            .off() //remove original event handler
            .click(function() { alert("you already voted!");});
    });
    

    Get the sibling of the parent, then get the script-vote <a> element inside it.