Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversing the DOM using jQuery

Tags:

jquery

Upon a click on an IMG, I would like to get to the next subsequent DIV so that the DIVs content can either be displayed or hidden depending on its current display state.

This is an HTML snippet:

<div>
  <span class="expand"><img src="images/plus.gif"></span>
  <span>Subject Heading</span>
</div>
<div class="record hidden">Display or Hide this text</div>

I have some code (provided in another answer on this site) for doing this in a table. Would I set an event listener for the img or the containing span? not sure how to use parent(), next(), sibling() functions to get around....

Also, how do you test if your navigation is getting to the right element? can you use an alert to display the id or value?

Any help is appreciated Thanks

like image 927
Jay Corbett Avatar asked Jan 21 '26 21:01

Jay Corbett


2 Answers

A cleaner approach is to toggle the image's parent's class between collapsed and expanded then in your css you can use contextual selectors to hide nested divs within collapsed ones.

Just my 2 cents.

like image 185
Allain Lalonde Avatar answered Jan 24 '26 10:01

Allain Lalonde


Here's a working example:

<script type="text/javascript" src="../jquery-1.2.6.min.js"></script>

<div>
  <span class="expand"><img src="x.jpg"></span>
  <span>Subject Heading</span>
</div>
<div class="record hidden">Display or Hide this text</div>

<script type="text/javascript">
    $(document).ready(function(){
        $('.expand img').toggle(
        function(){
            $(this).parent().parent().next().hide();
        },
        function(){
            $(this).parent().parent().next().show();
        });
    });
</script>

Note that I'm using parent twice because the event is added to the image, whose parent is the span, whose parent is the div.

like image 23
Adam Tuttle Avatar answered Jan 24 '26 10:01

Adam Tuttle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!