Jquery closest doesn't want to work

I repeated the image on the page with the div next to it as follows:

<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 mapping: not by default. when "prodQuestionMark" clicks, I want vuQuestionBubble to appear next to it. ive put this code below.

 $(document).ready(function () { $('.prodQuestionMark').click(function () { $(this).closest('vuQuestionBubble').show(); }); }); 

it doesn't seem to work ... the click event works, and I can select the parent div with .parent, but can not seem to interact with the closest div ... any ideas?

+4
source share
5 answers

closest looking for ancestors, not brothers and sisters; also missing in your selector . at the beginning (you tell him to look for the vuQuestionBubble element, where you really mean the div with the class "vuQuestionBubble").

With your current structure you can use the next , because the div with "vuQuestionBubble" is the next element. However, if you ever change the structure and place something in between, next will not work for you.

I would 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(); }); }); 

This will find the first div with the class "vuQuestionBubble" that follows img as a sister, even if it is not the one next to img and therefore your code is less prone to maintenance problems if the markup changes slightly.

+7
source

The closest function finds the closest ancestor to an element. You really need to use .next('.vuQuestionBubble') .

+4
source

vuQuestionBubble - class

 $(this).closest('vuQuestionBubble').show(); => $(this).closest('.vuQuestionBubble').show(); 
+1
source

Description: Get the first ancestor of an element that matches the selector, starting from the current element and progressing through the DOM tree

Translation: The closest thing, apparently, is to the ancestors, not brothers and sisters.

ref: http://api.jquery.com/closest/

Take a break, take kit-kat.

0
source

closest moves to the ancestor element, so try siblings('vuQuestionBubble')

0
source

Source: https://habr.com/ru/post/1342626/


All Articles