简体   繁体   中英

How to set the HTML of an element's sibling with JQuery

I have a DIV block with 3 DIV elements: upvote, votes, and downvote. When I click on upvote or downvote and call parent.html(html) within a JQuery block of code it overlays the vote count over the upvote or downvote icon. Which JQuery call would I use to gain access to the DIV class, "votes"? Would I find the parent of the parent element and then search for the "votes" class? Are there any ways to find an element's siblings by name? Sorry for the newbie question but I am still very new to JQuery!

Assuming your mark-up is approximately:

<div>
    <div class="upvote">vote up</div>
    <div class="votes">0</div>
    <div class="downvote">vote down</div>
</div>

You could use either:

$('.upvote').siblings('.votes');

Or:

$('.upvote').parent().find('.votes');

References:

  1. siblings() : JS Fiddle ,
  2. parent() ,
  3. find() .


Edited in response to question from OP (in comments):

Ohhhh no it's not a problem with there being more than one sibling '.votes' div. The problem is that there are more than one submissions on a given page and when you upvote one the rest get upvoted as well. I think this is why I need to use $this or something to only use the selected submission. Any ideas?

I'm not sure what, exactly, you mean by 'more than one submissions on a given page,' but I'm assuming you mean, simply, that there are multiple voting elements on the page. If that's the case (and I'm assuming the mark-up is consistently as I approximated in the first part of this answer), you can use:

 $('.upvote').click( function(){ $(this).siblings('.votes'); // this is just a selector, it won't 'do' anything // other than select the element. }); 

There are several different ways to access specific siblings in jQuery. Have a look at them all . You probably want siblings() .

$('selector').siblings('.votes')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM