Reputation: 385
I have repeated down the page an image with a div next to it like this:
<img src="/img/productspage/questionMark.jpg" class="prodQuestionMark" />
<div class="vuQuestionBubble">
<p>this is where text for the text will go</p>
</div>
vuQuestionBubble
has a style display:none by default. when 'prodQuestionMark' is clicked i want the vuQuestionBubble next to it to show. ive put this code at the bottom.
$(document).ready(function () {
$('.prodQuestionMark').click(function () {
$(this).closest('vuQuestionBubble').show();
});
});
it doesn't seem to work... the click event is working and i can select the parent div with .parent but cant seem to interact with the closest div... any ideas?
Upvotes: 4
Views: 2604
Reputation: 89
vuQuestionBubble
is a class
$(this).closest('vuQuestionBubble').show();
=>
$(this).closest('.vuQuestionBubble').show();
Upvotes: 1
Reputation: 7507
Description: Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree
Translated: Closest apparently gets ancestors, not siblings.
ref: http://api.jquery.com/closest/
Have a break, have a kit-kat.
Upvotes: 0
Reputation: 36999
The closest
function finds the closest ancestor to the element. You actually need to use .next('.vuQuestionBubble')
.
Upvotes: 4
Reputation: 1074385
closest
looks for ancestors, not siblings; also, your selector is missing a .
at the beginning (you're telling it to look for a vuQuestionBubble
element, where you really mean a div
with the class "vuQuestionBubble").
With your current structure, you can use next
because the div with the "vuQuestionBubble" is the very next element. However, if you ever change your structure and put something between them, next
won't work for you.
I'd probably use nextAll("div.vuQuestionBubble:first")
or nextAll(".vuQuestionBubble:first")
(links: nextAll
, :first
):
$(document).ready(function () {
$('.prodQuestionMark').click(function () {
$(this).nextAll('div.vuQuestionBubble:first').show();
// Or without `div`:
//$(this).nextAll('.vuQuestionBubble:first').show();
});
});
That will find the first div with the class "vuQuestionBubble" that follows the img
as a sibling, even if it's not the one right next to the img
, and so makes your code less susceptible to maintenance issues if the markup changes slightly.
Upvotes: 7
Reputation: 6602
closest
traverses to ancestor element, so try siblings('vuQuestionBubble')
Upvotes: 0